Model Validation
Both model binding and model validation occur before the execution of a controller action or a Razor Pages handler method.
Model State
For web apps, it's the app's responsibility to inspect ModelState.IsValid
and react appropriately. ModelState
represents errors that come from two subsystems: model binding and model validation.
Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.
Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5.
Web API controllers don't have to check ModelState.IsValid
if they have the [ApiController]
attribute. In that case, an automatic HTTP 400 response containing error details is returned when model state is invalid.
Validation attributes
[ValidateNever]: Indicates that a property or parameter should be excluded from validation.
[CreditCard]: Validates that the property has a credit card format. Requires jQuery Validation Additional Methods.
[Compare]: Validates that two properties in a model match.
[EmailAddress]: Validates that the property has an email format.
[Phone]: Validates that the property has a telephone number format.
[Range]: Validates that the property value falls within a specified range.
[RegularExpression]: Validates that the property value matches a specified regular expression.
[Required]: Validates that the field isn't null. See
[Required]
attribute for details about this attribute's behavior.[StringLength]: Validates that a string property value doesn't exceed a specified length limit.
[Url]: Validates that the property has a URL format.
[Remote]: Validates input on the client by calling an action method on the server. See
[Remote]
attribute for details about this attribute's behavior.
Last updated