In ASP.NET Core MVC views, how do DataAnnotations become client-side validation rules, and what does a custom ValidationAttribute need to join them?
answer
- adapters emit data-val-* attributes
- jquery-validation-unobtrusive reads them
- _ValidationScriptsPartial on the page
- IClientModelValidator.AddValidation
- [Remote] passes on the server
basics
~20 sMVC 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.
solid answer
~40 sWhen a view renders an input for a model property, MVC asks the validation attribute adapters for client rules. Built-in adapters exist for `[Required]`, `[StringLength]`, `[Range]`, `[RegularExpression]`, `[Compare]`, `[MinLength]`, `[MaxLength]`, `[EmailAddress]`, `[Phone]`, `[Url]`, `[CreditCard]` and `[FileExtensions]`; each writes attributes such as `data-val="true"`, `data-val-range-min="16"` and the message. The templates' `_ValidationScriptsPartial` loads jQuery Validation and jQuery Validation Unobtrusive, which read those attributes and block the submit. A custom attribute gets no client rule by default: implement `IClientModelValidator.AddValidation` to merge `data-val-*` attributes and register a jQuery Validation method that understands them. `[Remote]` calls an action over AJAX, but its server-side `IsValid` always returns true, so the server must re-check. Client rules are a convenience; `ModelState` on the server stays the authority.
go deeper
Know that DataAnnotations give instant browser feedback through jQuery validation scripts, and that the server still validates every post.
Explain the adapter to data-val-* to unobtrusive script chain and list which built-in attributes have client rules.
Add client support to custom rules with IClientModelValidator plus a script, and design server re-checks for [Remote] and other client-only logic.
Decide how much validation to mirror on the client against the cost of keeping two rule sets in sync, especially for SPA or mobile clients.
## The path from attribute to browser Client-side validation in ASP.NET Core MVC and Razor Pages is a rendering feature, not a second validator: 1. A view renders an input for a property, for example the `Age` field of the gym sign-up form. 2. MVC's **client model validator providers** look at the property's attributes. For DataAnnotations, `ValidationAttributeAdapterProvider` maps each attribute to an **adapter**. 3. The adapter's `AddValidation` writes **`data-val-*`** HTML attributes on the input. 4. **jQuery Validation** plus **jQuery Validation Unobtrusive**, loaded by the templates' `_ValidationScriptsPartial.cshtml`, parse those attributes when the page loads and validate before submit. For `[Range(16, 99)]` on `Age`, the rendered input carries `data-val="true"`, `data-val-range="..."` (the message), `data-val-range-min="16"` and `data-val-range-max="99"`. `HtmlHelperOptions.ClientValidationEnabled`, which controls this rendering, defaults to `true`. ## Which attributes come with client rules The built-in adapter provider recognises: - `[Required]`, `[StringLength]`, `[MinLength]`, `[MaxLength]` - `[Range]`, `[RegularExpression]`, `[Compare]` - `[EmailAddress]`, `[Phone]`, `[Url]`, `[CreditCard]`, `[FileExtensions]` Anything else, including a custom attribute and every `IValidatableObject` rule, runs only on the server unless you add client support. Non-nullable reference types get client rules too, because MVC treats them as `[Required(AllowEmptyStrings = true)]`. ## Making a custom attribute work in the browser There are two routes: | Route | What you write | When to prefer it | |---|---|---| | Implement `IClientModelValidator` on the attribute | `AddValidation(ClientModelValidationContext context)` that merges `data-val` and `data-val-<rule>` entries | the attribute is yours and simple | | Write an adapter (`AttributeAdapterBase<TAttribute>`) and register a custom `IValidationAttributeAdapterProvider` | an adapter class plus a provider that returns it | the attribute lives in a library without a reference to MVC | ```csharp public sealed class MinimumAgeAttribute(int years) : ValidationAttribute, IClientModelValidator { public int Years { get; } = years; public override bool IsValid(object? value) => value is not int age || age >= Years; public void AddValidation(ClientModelValidationContext context) { context.Attributes.TryAdd("data-val", "true"); context.Attributes.TryAdd("data-val-minimumage", FormatErrorMessage(context.ModelMetadata.GetDisplayName())); context.Attributes.TryAdd("data-val-minimumage-years", Years.ToString()); } } ``` The HTML attributes alone do nothing: the page also needs a small script that registers a `minimumage` method with jQuery Validation and an unobtrusive adapter that reads `data-val-minimumage-years`. Until both exist, the rule silently runs only on the server. ## `[Remote]`: a browser-only call to the server `[Remote(action: "IsEmailFree", controller: "Memberships")]` makes jQuery Validation call that action over AJAX as the user types, which suits "email already registered" checks. On the server, though, `RemoteAttribute`'s `IsValid` always returns `true`. A client that skips JavaScript, or calls the endpoint directly, bypasses the check, so the action must repeat it and use `ModelState.AddModelError` when it fails. ## Why the server stays the authority - Client scripts can be disabled, modified or skipped by any HTTP client. - Client and server semantics differ in places: jQuery Validation treats a whitespace-only string as present, while the server's `[Required]` rejects it. - Only server-side `ModelState` decides whether to save. Client rules exist to give feedback before a round trip. ## What interviewers listen for - The adapter, `data-val-*`, unobtrusive-script chain. - Which attributes have built-in client rules and that custom ones do not. - `IClientModelValidator` plus a JavaScript method for custom rules. - `[Remote]` passing on the server, and the server as the final check.
- A custom [MinimumAge] attribute works on the server but the form submits without a client error; what is missing?Either the attribute does not implement `IClientModelValidator` (or have an adapter), so no `data-val-minimumage` attributes are rendered, or the attributes are rendered but no jQuery Validation method and unobtrusive adapter named `minimumage` were registered. Both halves are needed; without them the rule runs only when the form reaches the server.
- Why must the server repeat a [Remote] email-availability check?`RemoteAttribute` only tells jQuery Validation which URL to call; its server-side `IsValid` always returns `true`. Any client without the script, or a direct POST, skips the AJAX call. The action has to query for the email again and add a `ModelState` error when it is taken.
- Every ValidationAttribute, including custom ones, is enforced in the browser automatically.
- IValidatableObject rules are translated into JavaScript by MVC.
- [Remote] also blocks invalid values when the form reaches the server.
- With client validation enabled, server-side ModelState checks are redundant.
- jQuery Validation and the server agree on whitespace-only required strings.