In ASP.NET web form, developers use validators to verify the data. ASP.NET MVC provides data annotations that help validate the data. This process of verification includes a set of attributes that we apply to the model classes to guarantee data validity. This is a declarative approach, making it easy validate model classes. Let's see how to apply validations in ASP.NET MVC using data annotations.
The following line sets UserName as the required value.
- [Required StringLength(50)]public string UserName { get; set; }
In the code above we have created the UserName property as the required field. Its length should not be greater than 50 characters. If we don't enter a value or enter a UserName field greater than 50 characters, ASP.NET MVC will throw a Model validation error. This is a simple process, as you can see.
Another important validation attribute is the range. Sometimes we want to specify the range within which the value should be. We specify it using the range attribute. In this attribute we specify the minimum and the maximum allowed value for the property the range attribute is being applied to.
- [Range(1,50)]public decimal Price { get; set; }
The code above will restrict the allowed values for the Price property within the range of 1 to 50. We can specify the custom error message displayed rather than the default error message displayed by using the ErrorMessage property. Every validation attribute provides the ErrorMessage property for specifying the custom error message to be displayed.
- [Range(1,50,ErrorMessage="Value lies outside the 1 to 50 range")]public decimal Price { get; set; }
The code above displays the custom error message instead of the built-in error message. When we add the TextBox for the declared Price property, if the user tries to enter a value more than 50, the custom error message assigned to ErrorMessage property will be displayed. We can declare the TextBox for the Price property as:
- @Html.TextBoxFor(x=>x.Price)
To display the actual validation error we use the following code:
- @Html.ValidationMessageFor(x=>x.Price)
Another useful method, ValidationSummary, can be used to display all the validation errors in one place.
- @Html.ValidationSummary()
If we use the code above, all of the validation error messages will be displayed in one place. We need to import the System.ComponentModel.DataAnnotations namespace to use these data annotations.