Breaking

Friday, July 31, 2020

Data Annotation and their types in MVC ?

mvc
Data Annotations are nothing but certain validations that we put in our models to validate the input from the user. ASP.NET MVC provides a unique feature in which we can validate the models using the Data Annotation attribute. Import the following namespace to use data annotations in the application.
System.ComponentModel.DataAnnotations
It is very easy to use and the code becomes much cleaner as compared to normal ASP.NET validators.
Let us understand some of the validator attributes that we can use in MVC.
Types of Data Annotations in ASP.NET MVC
Required
This attribute specifies that the value is mandatory and cannot be skipped.
Syntax
[Required(ErrorMessage="Please enter name"),MaxLength(30)]
DataType
This attribute is used to specify the datatype of the model.
Syntax
[DataType(DataType.Text)]
Range
Using this attribute we can set a range between two numbers.
Syntax
[Range(100,500,ErrorMessage="Please enter correct value")]
StringLength
Using this attribute we can specify maximum and minimum length of the property.
Syntax
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
DisplayName
Using this attribute we can specify property name to be displayed on view.
Syntax
[Display(Name="Student Name")]
MaxLength
Using this attribute we can specify maximum length of property.
Syntax
[MaxLength(3)]
Bind
This attribute specify fields to include or exclude for model binding.
Syntax
[Bind(Exclude = "StudentID")]
DisplayFormat
This attribute allows us to set date in the format specified as per the attribute.
Syntax
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
RegularExpression
We can set a regex pattern for the property. For ex: Email ID.
Syntax
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]

No comments:

Post a Comment