In this article we will learn what is model attributes or how to use Model attributes or why use Model attributes or how to use model validation attribute in mvc with example.


ASP.NET MVC model can validate itself on the view at client side and in the controller action method in the server side by using Data Annotation attribute classes. To apply validation to the properties of the model, we can use validation attributes.

Following are ASP.NET MVC model validation attributes that is applied to the properties of the model. 

[Required] - to mark a property as mandatory

[Required(ErrorMessage = "Please write your Name")]
 public string Name { get; set; }

[StringLength(max)] - to limit the maximum and minimum number of characters allowed

[StringLength(20,MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
public string FirstName { get; set; }

[Range(min, max)] - minimum and maximum numberic valud allowed

[Range(0, 10, ErrorMessage = "The value must be between 0 and 10")]
public int Age { get; set; }

[DataType(DataType.type)] - to set the type of data allowed in this property

 public string Salary { get; set; }

[Compare("OtherPropertyName")] - two property must have the same name. This property and "OtherPropertyName" must have the same value. Generally used to get password and confirm password

[Required(ErrorMessage = "Password is required")]       
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
public string ConfirmPassword { get; set; }

 [RegularExpression("pattern")] - property value must match the specified pattern


I hope it will help to you.

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like