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.

Introduction:

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.

Data Annotation Attribute

There are many Data Annotation attributes that can be used to validate data.

DataType:

Data Type can be used to Specify the datatype of a property.

DisplayName:

This can be used to specify the display name for a model property.

DisplayFormat:

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.

Required:

This attribute is used to ensure that the property has not been left empty.

Range:

This attribute ensures that the value of the model property should lie between the maximum and minimum permissible length.

StringLength:

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.

EmailAddress :

This attribute can be used to validate that the value of the email property is a correct email format or not.

Url:

This property is used to ensure that the given URL is a valid URL or not.

RegularExpression :

This attribute can be Used to Validate a value against a specified regular expression.

ScaffoldColumn:

This attribute can be used to specify fields for hiding from editor forms.

Bind:

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.

Data Annotation Attribute

Step 2- Choose an Internet Application as in below snapshot.

Data Annotation Attribute

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.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DataAnnotationDemo.Models
{
[Bind(Exclude = "EmployeeID")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmployeeID { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100, MinimumLength = 5)]
public String EmployeeName { get; set; }
[Required(ErrorMessage = "Employee Address is required")]
[StringLength(250)]
public string EmployeeAddress { get; set; }
[Required(ErrorMessage = "Age is required")]
[Range(18, 40, ErrorMessage = "Age must be between 18 and 40")]
public int EmployeeAge { get; set; }
[Required(ErrorMessage = "Please enter correct email address")]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
public string EmailID { get; set; }
}
}

Step 4- Goto Solution Explorer and navigate to folder Views>Home and open Index,cshtml file. Replace the existing code with the following code.

@model DataAnnotationDemo.Models.Employee

@{
    ViewBag.Title = "Index";
    
}


<h2>Index</h2>


@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    
<fieldset>

<legend>Employee</legend>


<div class="editor-label">
            @Html.LabelFor(model => model.EmployeeName)
        </div>


<div class="editor-field">
            @Html.EditorFor(model => model.EmployeeName)
            @Html.ValidationMessageFor(model => model.EmployeeName)
        </div>


<div class="editor-label">
            @Html.LabelFor(model => model.EmployeeAddress)
        </div>


<div class="editor-field">
            @Html.EditorFor(model => model.EmployeeAddress)
            @Html.ValidationMessageFor(model => model.EmployeeAddress)
        </div>


<div class="editor-label">
            @Html.LabelFor(model => model.EmployeeAge)
        </div>


<div class="editor-field">
            @Html.EditorFor(model => model.EmployeeAge)
            @Html.ValidationMessageFor(model => model.EmployeeAge)
        </div>


<div class="editor-label">
            @Html.LabelFor(model => model.EmailID)
        </div>


<div class="editor-field">
            @Html.EditorFor(model => model.EmailID)
            @Html.ValidationMessageFor(model => model.EmailID)
        </div>



            <input type="submit" value="Create" />
        

    </fieldset>

}


<div>
    @Html.ActionLink("Back to List", "Index")
</div>


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Run the application and verify the output of the application.

Data Annotation Attribute

You can download the complete source code for the example from here.

Conclusion:

Hope you understand this tutorial of Data Annotation Attribute in ASP.NET MVC and how to validate model property with Data Annotation Attribute.

View More:

Thank You.

Leave a Comment