ASP.NET Core Interview Question #118

How does model validation work in ASP.NET Core?

Routing, Controllers & Model Binding Mid-Level Intermediate

Quick Interview Answer

Model validation runs after model binding and evaluates validation rules associated with the bound model.

Detailed Explanation

Model validation runs after model binding and evaluates validation rules associated with the bound model.

Data annotation attributes such as Required, StringLength, Range, EmailAddress, and Compare are commonly used. Custom validation can be implemented when built-in attributes are insufficient.

Validation protects the application's input contract, but business rules that require domain knowledge or database state should normally be enforced in the appropriate application or domain layer as well.

Code Example

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; } = string.Empty;

    [Required]
    [StringLength(100, MinimumLength = 8)]
    public string Password { get; set; } = string.Empty;
}