ASP.NET Core MVC Interview Question #40

How can you add a custom validation error to ModelState?

Controllers, Actions, Model Binding & Action Results Junior Beginner

Quick Interview Answer

A controller can add an error manually with ModelState.AddModelError. This is useful for validation that depends on application logic or multiple fields, such as checking whether a username is already registered.

Detailed Explanation

A controller can add an error manually with ModelState.AddModelError. This is useful for validation that depends on application logic or multiple fields, such as checking whether a username is already registered.

For complex reusable validation rules, consider placing the rule in an appropriate validation or application service rather than growing controllers with validation logic.

Code Example

if (await _userService.EmailExistsAsync(model.Email))
{
    ModelState.AddModelError(
        nameof(model.Email),
        "This email address is already registered.");
}