Data Validation in MVC

Validation using Data Annotation Attributes

ASP.NET MVC includes built-in attribute classes in the System.ComponentModel.DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.


The following table lists all the data annotation attributes which can be used for validation.

AttributeUsage
RequiredSpecifies that a property value is required.
StringLengthSpecifies the minimum and maximum length of characters that are allowed in a string type property.
RangeSpecifies the numeric range constraints for the value of a property.
RegularExpressionSpecifies that a property value must match the specified regular expression.
CreditCardSpecifies that a property value is a credit card number.
CustomValidationSpecifies a custom validation method that is used to validate a property.
EmailAddressValidates an email address.
FileExtensionValidates file name extensions.
MaxLengthSpecifies the maximum length of array or string data allowed in a property.
MinLengthSpecifies the minimum length of array or string data allowed in a property.
PhoneSpecifies that a property value is a well-formed phone nu