skip to content

DataAnnotations & ModelState

DataAnnotations, custom ValidationAttribute classes and IValidatableObject fill ModelState after binding. Interviewers ask when ModelState.IsValid is checked for you and when it is not.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core MVC, how do [Required], [StringLength], [Range] and [RegularExpression] on a sign-up model feed ModelState.IsValid, and who checks it?

level: juniorimportance: must knowfreq 82%

answer

  1. after binding, before the action
  2. errors keyed by property name
  3. views and pages: you check
  4. [ApiController]: automatic 400
  5. [Range] lets null through

basics

~20 s

After model binding and before the action runs, MVC evaluates every validation attribute and records failures in ModelState under the property's key. In controllers with views and in Razor Pages you check ModelState.IsValid yourself; [ApiController] returns a 400 for you.

solid answer

~40 s

MVC validates the bound model between binding and action execution. Each DataAnnotations attribute (`[Required]`, `[StringLength(60, MinimumLength = 2)]`, `[Range(16, 99)]`, `[RegularExpression(...)]`) runs against its property, and each failure becomes an entry in `ModelState` keyed by the property name, next to any binding errors such as "The value 'abc' is not valid for Age.". Nothing stops the action automatically in a controller with views or a Razor Page: you write `if (!ModelState.IsValid) return View(model);` and redisplay the form. In a controller marked `[ApiController]`, a built-in action filter checks `ModelState.IsValid` first and returns a 400 with validation problem details, so the action never sees invalid input. Of these attributes, only `[Required]` rejects null; `[Range]` treats null as valid, so a nullable property needs both.

go deeper

for a junior

Know the four common attributes, that failures land in ModelState, and the if (!ModelState.IsValid) return View(model) pattern for forms.

for a middle

Explain the binding, validation, action order, why [ApiController] makes the inner check redundant, and why [Range] needs [Required] for presence.

for a senior

Combine attribute errors with AddModelError for data-dependent rules, keep messages consistent, and know the 200-error and depth-32 caps.

for a principal

Decide which rules live in request-model attributes and which in the domain layer, so validation stays consistent across forms, APIs and background imports.

## Where validation sits in the request ASP.NET Core MVC handles a form post or API call to an action in a fixed order: 1. **Model binding** fills the action's parameters from the route, query string, form or body. 2. **Model validation** walks the bound objects and runs every validator it finds. 3. **Action filters** run, and then the **action** itself. A failed rule never throws. Validation writes into `ModelState`, a `ModelStateDictionary` exposed on `ControllerBase` and `PageModel`. Each entry is keyed by the model name of the value (`FullName`, `Age`, or `Address.City` for a nested property) and holds the attempted value plus any errors. `ModelState.IsValid` is `true` only when every entry ended up valid (or had validation skipped); any error, or an entry never validated, makes it `false`. ## The four everyday attributes All four live in `System.ComponentModel.DataAnnotations`: | Attribute | Checks | Example on the gym sign-up | |---|---|---| | `[Required]` | value is not null (and, for strings, not empty unless `AllowEmptyStrings = true`) | `FullName`, `Email` | | `[StringLength(max, MinimumLength = min)]` | string length within bounds | `[StringLength(60, MinimumLength = 2)]` on `FullName` | | `[Range(min, max)]` | numeric or comparable value within bounds | `[Range(16, 99)]` on `Age` | | `[RegularExpression(pattern)]` | string matches a pattern | `[RegularExpression("^[0-9+ ]{7,16}$")]` on `Phone` | ```csharp public class MembershipSignUp { [Required, StringLength(60, MinimumLength = 2)] public string? FullName { get; set; } [Required, EmailAddress] public string? Email { get; set; } [Range(16, 99)] public int Age { get; set; } [RegularExpression("^[0-9+ ]{7,16}$")] public string? Phone { get; set; } } ``` **Of these four, only `[Required]` rejects a missing (null) value.** `[Range]` returns valid for `null` or an empty string, so an `int? Age` with only `[Range(16, 99)]` passes when the field is omitted. Combine `[Required]` with the others whenever the value must be present. ## Who checks `ModelState.IsValid` The answer depends on the kind of endpoint: - **Controllers with views (`Controller`) and Razor Pages.** Nothing short-circuits. The action runs with an invalid model, and it is your job to check and redisplay: ```csharp [HttpPost] public IActionResult SignUp(MembershipSignUp model) { if (!ModelState.IsValid) return View(model); // the form shows the errors // save and redirect return RedirectToAction(nameof(Welcome)); } ``` - **Controllers marked `[ApiController]`.** A built-in action filter runs before your action, sees `ModelState.IsValid == false`, and returns a **400 Bad Request** with a validation problem details body. The action body never executes, so an `IsValid` check inside it is dead code. Which other behaviours `[ApiController]` switches on is a controller-conventions topic. - **Minimal API handlers** do not use MVC's `ModelState` at all; their validation is a separate mechanism. ## Practical details - **Binding errors share the dictionary.** `Age=abc` cannot become an `int`; binding adds an error for `Age` before validation runs, and `IsValid` is false either way. - **Messages.** `ErrorMessage` accepts placeholders: for `[StringLength]`, `{0}` is the display name, `{1}` the maximum and `{2}` the minimum. `[Display(Name = "Full name")]` changes `{0}`. - **Adding your own errors.** `ModelState.AddModelError("Email", "That email is already a member.")` lets the action add checks that need a database, and the view shows them like attribute errors. - **Limits.** MVC stops adding errors after `MvcOptions.MaxModelValidationErrors` (200 by default) and stops recursing at `MaxValidationDepth` (32). - **Re-validating.** After changing a bound object in code, `ModelState.ClearValidationState(key)` followed by `TryValidateModel(model)` runs validation again. ## What interviewers listen for - The ordering: binding, validation, then action, and that validation records rather than throws. - That `[ApiController]` checks `IsValid` for you while views and pages do not. - That, among these attributes, `[Required]` is the one that checks for null.

  • Why is an IsValid check inside an [ApiController] action usually dead code?
    The `[ApiController]` convention adds an action filter that runs before the action, checks `ModelState.IsValid` and, when it is false, sets the result to a 400 with validation problem details. The action body is skipped, so a check inside it only matters if the filter was turned off with `ApiBehaviorOptions.SuppressModelStateInvalidFilter`.
  • How do you report a rule that needs the database, such as a duplicate email, through ModelState?
    Run the query in the action (or a service it calls) and call `ModelState.AddModelError("Email", "That email is already a member.")` when it fails. The error is keyed like an attribute error, so `IsValid` turns false and the view, or `ValidationProblem()` in an API action, presents it with the others.

  • Every MVC controller returns 400 automatically when ModelState is invalid.
  • Validation runs lazily the first time the action reads ModelState.IsValid.
  • [Range(16, 99)] on an int? property fails when the field is omitted.
  • A failed DataAnnotations rule throws a ValidationException inside the action.
  • Binding errors and validation errors are reported in separate dictionaries.
open as a page

In ASP.NET Core MVC views, how do DataAnnotations become client-side validation rules, and what does a custom ValidationAttribute need to join them?

level: middleimportance: should knowfreq 35%

basics

~20 s

MVC maps each built-in attribute to an adapter that renders data-val-* HTML attributes on the input, and jQuery Validation Unobtrusive enforces them in the browser. A custom attribute must implement IClientModelValidator and ship a matching JavaScript rule.

open as a page

In an ASP.NET Core MVC model, when would you write a custom ValidationAttribute and when implement IValidatableObject for a cross-field sign-up rule?

level: middleimportance: should knowfreq 50%

basics

~20 s

Write a ValidationAttribute for a rule you reuse on many properties; implement IValidatableObject for a rule that compares fields of one class, such as under-18 members needing a guardian. MVC runs IValidatableObject only after the property attributes pass.

open as a page

In ASP.NET Core MVC, why does [Required] on a non-nullable int never fail, while a non-nullable string property fails with no attribute at all?

level: middleimportance: should knowfreq 52%

basics

~20 s

[Required] only detects null, and an int is never null, so a missing value becomes 0 and passes. With nullable reference types enabled, MVC treats a non-nullable string as [Required(AllowEmptyStrings = true)], and empty strings bind as null, so it fails.

open as a page

In an ASP.NET Core [ApiController], how do you customise the automatic invalid-ModelState response with InvalidModelStateResponseFactory, and what can that factory not change?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Set ApiBehaviorOptions.InvalidModelStateResponseFactory through AddControllers().ConfigureApiBehaviorOptions; it receives the ActionContext and returns the IActionResult sent instead of running the action. It only affects [ApiController] controllers and runs before your ordinary action filters.

open as a page