Validations in MVC


Data Annotations help us to validate any properties in the model in MVC. Data annotations are nothing but attributes which can be applied on model properties.

For example, in the below code snippet we have a simple Employee class with a property EmployeeCode. This EmployeeCode property is tagged with a Required data annotation attribute. Which mean EmployeeCode is mandatory field.

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.

We can use the ValidationSummary method from the Html helper class to display all the messages at a single place.

few other examples of data annotation attributes for validation in MVC are as given bellow.

Checking  String Length:

Use the RegularExpression attribute.

If you want to check whether the numbers are in range, you can use the Range attribute.

compare the value of one field with another field, we can use the Compare attribute.

In case you want to get a particular error message against ModelState , you can use the Errors collection.

If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object is valid or not.

In case you want add errors in the controller you can use the AddModelError function.