MVC provides a Data annotation attributes to validate the user input. All the attributes are available in“System.ComponentModel.DataAnnotations” name space. Similar to Asp.Net web form validation controls, MVC provides different attributes to validate the data
Required:
This validation makes sure that user is providing the value to the property. It will raise the error if either property value is null or empty
Code:
Output:
StringLength:
This validation forces the user to give only specific length of string as input. In the below example user is restricted to give name with minimum 3 and maximum 100 character. If user gives more than this validator will specify the error message mention in “ErrorMessage” property. If you have not mention any ErrorMessage property, system will display default error message for the validation attribute
Output:
Range:
This Range attribute specifies minimum and maximum constraints for a numerical value. Below example “Age” property will accept the value between 18 and 60
Code:
Output:
RegularExpression:
This attribute allow mentioning any regular express as validation logic for the property. Below example specify how to validate the email expression. By default system will display the default warning message, set the “ErrorMessage” property to define user friendly message.
Code:
Output: