liveBook · Manning

Validation attribute

As explained in ASP.NET Core in Action, 3e

A custom validation attribute is an application-defined attribute that implements a specialized validation rule, typically by deriving from ValidationAttribute.

A custom validation attribute adds an application-specific rule when the built-in DataAnnotations attributes are not enough. Derive from ValidationAttribute, override IsValid, and apply the attribute to binding-model properties. section 32.3 section 32.5

Build a property-level validation rule in three steps:

  • Define a ValidationAttribute subclass and accept rule configuration, such as an array of allowed currency codes. section 32.3

Restrict currency codes

A currency converter can annotate CurrencyFrom and CurrencyTo with CurrencyCode("GBP", "USD", "CAD", "EUR"). An input such as "£$%" makes ModelState invalid and produces the message "Not a valid currency code".

When validation depends on application data, obtain a service from ValidationContext inside IsValid. Constructor dependency injection is unavailable for custom validation attributes, so the service-locator approach uses GetRequiredService or GetService instead. section 32.5

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains derivation, IsValid, error results, reuse, and service lookup, while deferring complex cross-property business rules.
Examples
Uses a currency converter that accepts only GBP, USD, EUR, or CAD and rejects an invalid value such as £$%.
What it assumes
Assumes familiarity with C# properties and built-in DataAnnotations, while demonstrating custom validation from the ValidationAttribute base class.
What you can do after
Build it from scratch by defining, applying, and testing a reusable ValidationAttribute for application-specific property rules.
How it connects
Connects ValidationAttribute with DataAnnotations, model binding, ModelState, dependency injection, IValidatableObject, and FluentValidation.

Also explained in

Compare how 3 books explain validation attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.