Validation in ASP.NET MVC Using the Data Annotations

The validation of data is required in every web application to ensure that the user has entered the correct data. In ASP.NET web form developers use the validators to verify the data. Validators such as the required field validator ensures that the data is correct. ASP.NET MVC provides the Data Annotations that help validate the data. Data Annotation in ASP.NET MVC includes a set of attributes that we apply to the model classes to ensure data validity. So validation in ASP.NET MVC uses a declarative approach that makes it really easy to apply validation to model classes.

Let's see how to apply the validations in ASP.NET MVC using the data annotations.

The following line makes the UserName as the required value.

  1. [Required StringLength(50)]  
  2. public string UserName { getset; }
In the code above we have made the UserName property the required field and also its length should not be greater than 50 characters. If we enter the UserName field with more than 50 characters or without any value then ASP.NET MVC will throw a Model validation error. So as we can see its really easy to apply model validation in ASP.NET MVC.

Another important validation attribute is the range. Sometimes we want to specify the range of valid values within which the value should be. We specify it using the range attribute. In the range attribute we specify the minimum and the maximum allowed value for the property to which the range attribute is being applied.
  1. [Range(1,50)]  
  2. public decimal Price { getset; }
The code above will restrict the allowed values for the Price property to be within the range 1 to 50.

One important point is that we can specify the custom error message displayed instead of the default error message displayed using the ErrorMessage property. Every validation attribute provides the ErrorMessage property for specifying the custom error message to be displayed.
  1. [Range(1,50,ErrorMessage="Value lies outside the 1 to 50 range")]  
  2. public decimal Price { getset; }
The code above displays the custom error message instead of the built-in error message.

Now if in the view we add the TextBox for the preceding declared Price property and the user tries to enter the value more than 50 then the error message assigned to the ErrorMessage property will be displayed to the user. We can declare the TextBox for the Price property as:
  1. @Html.TextBoxFor(x=>x.Price)
And to display the actual validation error we use the following code:
  1. @Html.ValidationMessageFor(x=>x.Price)
There is one useful method, ValidationSummary, that we can use to display all the validation errors in one place.
  1. @Html.ValidationSummary()
If we use the code above then we will have all the validation error messages displayed in one place. We need to import the System.ComponentModel.DataAnnotations namespace to use the data-annotations.


Similar Articles