Introduction:

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.

Description: 

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

[DataType(DataType.Currency)]
 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")]       
[DataType(DataType.Password)]
public string Password { get; set; }
 
[Required(ErrorMessage = "Confirm Password is required")]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }

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

[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]



I hope it will help to you.

0 comments


Leave a comment

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

You may also like