In this tutorial, we are going to Learn Data Annotation Attribute for validating Model properties. As we are already familiar with the ASP.NET MVC in our previous tutorial. Let’s Start the tutorial for Data Annotation Attributes.
At the end of this tutorial, you will be able to understand the following terms:
- Data Annotation Attributes in ASP.NET MVC.
- How to validate Model Property using Data Annotation Attributes.
Data Validation is the primary requirement for any web application in nowadays. .Net provides Data Annotation attributes classes to validate Model Classes. Data Annotation classes exist under System.ComponentModel.DataAnnotations. Using Data Annotation Attribute classes we can define our rules over model classes to validate data.
There are many Data Annotation attributes that can be used to validate data.
Data Type can be used to Specify the datatype of a property.
This can be used to specify the display name for a model property.
Display format can be used to specify the display format for a model property. For e.g. we can specify different date formats for Date property.
This attribute is used to ensure that the property has not been left empty.
This attribute ensures that the value of the model property should lie between the maximum and minimum permissible length.
This attribute can be used to specify minimum and maximum length for the string model property. You can either specify the maximum length or maximum and minimum length for the string property.
This attribute can be used to validate that the value of the email property is a correct email format or not.
This property is used to ensure that the given URL is a valid URL or not.
This attribute can be Used to Validate a value against a specified regular expression.
This attribute can be used to specify fields for hiding from editor forms.
Bind attribute can be used to specify fields that need to include or exclude when adding parameter or form values to model properties.
Let’s understand this topic through an example:
The Example of Data Annotation Attribute in ASP.NET MVC:
Step 1- Create an ASP.NET MVC application called DataAnnotationDemo.
Step 2- Choose an Internet Application as in below snapshot.
Step 3- Goto Solution Explorer and right click on the Model folder and create a class called Employee. Here is the code for Employee.cs file.
Step 4- Goto Solution Explorer and navigate to folder Views>Home and open Index,cshtml file. Replace the existing code with the following code.
Run the application and verify the output of the application.
You can download the complete source code for the example from here.
Hope you understand this tutorial of Data Annotation Attribute in ASP.NET MVC and how to validate model property with Data Annotation Attribute.
- Introduction to ASP.NET MVC.
- CRUD Operation in ASP.NET MVC.
- Introduction to Entity Framework in .NET.
- CRUD Operation using Entity Framework in ASP.NET MVC.