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?
answer
- reusable per property vs one class
- IsValid(object?, ValidationContext)
- ValidationResult with member names
- class-level runs after properties pass
- ValidateComplexTypesIfChildValidationFails
basics
~20 sWrite 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.
solid answer
~40 sA custom `ValidationAttribute` overrides `IsValid(object? value, ValidationContext validationContext)` and returns `ValidationResult.Success` or a `ValidationResult` naming the member. It is reusable, declarative and can also feed client-side rules, which suits checks like "start date not in the past". `IValidatableObject.Validate(ValidationContext)` lives on the model and yields results for rules that span its properties, such as "members under 18 need a guardian name". Pass `new[] { nameof(GuardianName) }` so the error lands on that field rather than only in the summary. Ordering matters: MVC runs type-level validators, including `IValidatableObject`, only when the object's properties validated cleanly, unless `MvcOptions.ValidateComplexTypesIfChildValidationFails` is set. Both receive a `ValidationContext` whose service provider is the request's, so `GetService` works for small lookups.
code
csharp · 6 linesbuilder.Services.AddControllersWithViews(options =>
{
// run IValidatableObject and class-level attributes
// even when a property already failed
options.ValidateComplexTypesIfChildValidationFails = true;
});go deeper
Know that you can write your own attribute by inheriting ValidationAttribute, and that a model can validate itself with IValidatableObject.
Explain both signatures, how member names place an error on a field, and why the class rule appears only after property errors are fixed.
Choose attribute, class rule or action check by reuse and cost, keep I/O out of validators, and use ValidateComplexTypesIfChildValidationFails deliberately.
Decide which business invariants are enforced at the request edge and which belong to the domain model, so rules are not duplicated across layers.
## Two extension points in DataAnnotations Both types come from `System.ComponentModel.DataAnnotations`, and ASP.NET Core MVC runs both during model validation. | | Custom `ValidationAttribute` | `IValidatableObject` | |---|---|---| | Lives on | a property, parameter or class | the model class itself | | Signature | `ValidationResult? IsValid(object? value, ValidationContext validationContext)` | `IEnumerable<ValidationResult> Validate(ValidationContext validationContext)` | | Reuse | any model, any property | that one type | | Sees other fields | through `validationContext.ObjectInstance` (the containing object) | directly, as `this` | | Client-side rule | possible by also implementing `IClientModelValidator` | none | | When MVC runs it | with the property's other attributes | after the properties, only if they passed | ## A reusable attribute: start date not in the past ```csharp public sealed class NotInPastAttribute : ValidationAttribute { protected override ValidationResult? IsValid( object? value, ValidationContext validationContext) { if (value is not DateOnly start) return ValidationResult.Success; // let [Required] handle null var clock = validationContext.GetService<TimeProvider>() ?? TimeProvider.System; var today = DateOnly.FromDateTime(clock.GetLocalNow().DateTime); return start >= today ? ValidationResult.Success : new ValidationResult( $"{validationContext.DisplayName} cannot be in the past.", new[] { validationContext.MemberName! }); } } ``` Points worth saying aloud: - Return `ValidationResult.Success` for `null` and let `[Required]` own presence, the same convention the built-in attributes follow. - MVC builds the `ValidationContext` with `HttpContext.RequestServices` as its service provider, so `GetService<T>()` resolves request-scoped services. Keep that to cheap lookups; slow I/O in validation runs on every request. - `DisplayName` comes from `[Display(Name = ...)]`, which keeps messages consistent with labels. ## A class rule: under-18 members need a guardian ```csharp public class MembershipSignUp : IValidatableObject { public string FullName { get; set; } = ""; [Range(14, 99)] public int Age { get; set; } public string? GuardianName { get; set; } [NotInPast] public DateOnly StartDate { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Age < 18 && string.IsNullOrWhiteSpace(GuardianName)) yield return new ValidationResult( "Members under 18 need a guardian.", new[] { nameof(GuardianName) }); } } ``` ## The ordering rule that surprises people MVC's validation visitor validates the **children** of an object (its properties) first. Only if they all pass does it run the **type-level** validators, which include `IValidatableObject` and attributes placed on the class: 1. A sign-up posted with `Age = 15`, no guardian and a past `StartDate` shows only the start-date error. 2. The user fixes the date, resubmits, and only now sees the guardian error. That two-round experience is the default. Setting `MvcOptions.ValidateComplexTypesIfChildValidationFails = true` makes MVC run type-level validators even when properties failed, so all errors appear at once. ## Where the error appears - A `ValidationResult` with member names adds one `ModelState` entry per name, so the form shows it beside the field. - A result with **no** member names is keyed at the model's own level (an empty key for a top-level parameter bound without a prefix), so it appears only in a validation summary. ## Choosing between them - Same rule on many models, or a rule you want mirrored in the browser: **attribute**. - A rule about how this model's fields relate: **`IValidatableObject`**. - A rule that needs a database or another service call (email already registered): neither; do it in the action or service and call `ModelState.AddModelError`. ## What interviewers listen for - Both signatures, and `ValidationResult` with member names. - The properties-first ordering and the option that changes it. - Where each error is keyed, and keeping I/O out of validators.
- Why does the guardian error only appear after the user fixes the date field?MVC validates an object's properties first and runs type-level validators such as `IValidatableObject.Validate` only when every property passed. The invalid `StartDate` stops the class rule from running. Setting `MvcOptions.ValidateComplexTypesIfChildValidationFails = true` runs it anyway, so both errors show in one round.
- How can a custom ValidationAttribute compare its property with another property on the same model?Read the containing object from `validationContext.ObjectInstance`, cast it to the model type, and compare. MVC passes the container as the instance when it validates a property. It works, but it couples the attribute to one model, which is the signal that `IValidatableObject` is usually the clearer home for the rule.
- IValidatableObject.Validate runs even when property attributes already failed, by default.
- A ValidationResult without member names shows next to the first field of the form.
- Custom attributes cannot reach DI services, so they must new up dependencies.
- IValidatableObject rules are copied into client-side validation automatically.
- Checking for a duplicate email in the database belongs in a ValidationAttribute.