15 49.0138 8.38624 1 0 4000 1 https://codeisall.com 300
Data Annotations MVC

Data Annotation in MVC


In theĀ previous article, you have learned about what is Dependency Injection and how can we achieve this in MVC application.

In this article, you will learn about what is data annotation, types of data annotation and, how can we use them in MVC Project.

This article will be helpful to beginners and students who are learning MVC


  • You need to create an ASP.NET MVC Project (You can refer our article to create a new project), Or you can add this into the existing project also A SQL  server Installed where you can create a database.
  • An empty Database created on the SQL server.

What is Data Annotation?

Data annotations are attributes that can be applied to classes or class members to specify the relationship between classes and property data. it describe how the data is to be displayed in the UI, and it specify validation rules if any.

Data annotation is one type of validation that we put in our models to validate the input from the users.

In ASP .NET MVC we can validate the models using the Data Annotation attribute, that is an unique feature of ASP .NET MVC.

To use the data annotation in MVC System.ComponentModel.DataAnnotations namespace is needed to be imported.

Its very easy to apply and use in a MVC application and also less code to write as compare to any other validations.

Types of Data Annotations in ASP.NET MVC

There are many times of data annotations like Required, DataType, RegularExpression, Range, StringLength, DisplayName, MaxLength.


This is used to make a user input mandatory. And it can not be skipped.

[Required(ErrorMessage="Please enter first name"),MaxLength(30)]
public string FirstName {get;set;}


This is used to give range on any model property between two numbers.

[Range(1,100,ErrorMessage="Please enter correct value")]
public decimal Percentage {get; set;}


This is used to specify the datatype of the model property.

public string FirstName {get;set;}


This is used to specify the maximum and minimum length of the property.

[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
public string FirstName {get;set;}


Using this attribute we can specify property name to be displayed on view.

[Display(Name="Student Name")]
public string Name {get;set;}


This is used to specify maximum length of property.

public int Volume {get;set;}


This is used to set the date in the format specified as per the attribute.

[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
public string DOB {get;set;}


This is used to set a regex pattern for the property of model.

[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]
public string Email {get;set;}

How to use Data Annotation in MVC?

Lets take a register Employee form as an example and see how data annotation works in that form.

Step 1 :

Create a model called “EmployeeModel” as shown in below code snippet and also see how the data annotations are used on those model properties.


public class EmployeeModel
    public int Id { get; set; }
    [Required(ErrorMessage="Please enter First Name"), MaxLength(15)]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Please enter Last Name"), MaxLength(15,ErrorMessage ="Name must be shorter then 15 char")]
    public string LastName { get; set; }
    [Required(ErrorMessage = "Date of Birth is Required"),DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}"), Display(Name = "Date Of Birth")]
    public DateTime DOB { get; set; }
    [Required(ErrorMessage ="Please Enter Email"), RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid."), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required(ErrorMessage ="Salary is Required"),MaxLength(5,ErrorMessage ="Salary Length should be less then 6 digit")]
    public int Salary { get; set; }
    [Required(ErrorMessage ="Phone Number is required"),DataType(DataType.PhoneNumber)]
    public int PhoneNumber { get; set; }

Step 3:

Add a method in controller to display the registration form and also add one save method to save data in database as shown below.


public class HomeController : Controller
    public ActionResult Index()
        return View();
    public ActionResult Add()
        EmployeeModel model = new EmployeeModel();
        return View(model);
    public ActionResult Add(EmployeeModel model)
        using (var dBContext = new EmployeeDataEntities())
            Employee datamodel = new Employee();
            datamodel.FirstName = model.FirstName;
            datamodel.LastName = model.LastName;
            datamodel.DOB = model.DOB;
            datamodel.Salary = model.Salary;
            datamodel.PhoneNumber = model.PhoneNumber;
            datamodel.Email = model.Email;

        return RedirectToAction("Index");

Step 3 :

Right click on the Add method and add a view and replace the below code in the view file.


@model EmployeeManagement.Models.EmployeeModel
    Layout = "~/Views/Shared/_Layout.cshtml";

Add Employee

@using (Html.BeginForm("Add", "Home", FormMethod.Post, new { name = "EmployeeForm" })) { @Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(m => m.Id)
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control form-control-sm required", name = "EmpName" }) @Html.ValidationMessageFor(m => m.FirstName, "", new { @class = "text-danger col-form-label" })
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control form-control-sm required", name = "EmpName" }) @Html.ValidationMessageFor(m => m.LastName, "", new { @class = "text-danger col-form-label" })
@Html.TextBoxFor(m => m.DOB,"{0:dd/MM/yyyy}", new { @class = "form-control form-control-sm datepicker", @AutoComplete = "off", name = "EmpDOB" }) @Html.ValidationMessageFor(m => m.DOB, "", new { @class = "text-danger col-form-label" })
@Html.TextBoxFor(m => m.Email, new { @class = "form-control form-control-sm", @AutoComplete = "off" }) @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger col-form-label" })
@Html.TextBoxFor(m => m.Salary, new { @class = "form-control form-control-sm", @AutoComplete = "off"}) @Html.ValidationMessageFor(m => m.Salary, "", new { @class = "text-danger col-form-label" })
@Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control form-control-sm", @AutoComplete = "off"}) @Html.ValidationMessageFor(m => m.PhoneNumber, "", new { @class = "text-danger col-form-label" })
@section scripts { @Scripts.Render("~/bundles/jqueryval") $(document).ready(function () { $('.datepicker').datepicker({ format: 'mm/dd/yyyy' }); }); }

Then run the project and you will see the below form, now create you can test the validations as i have tested below.

I hope this article will help you to learn about data anotations and how to use it in MVC application. we will be happy to help you if you have any issues or queries. Comment your suggestions and issues and we will try to resolve it.

Dependency Injection in C#
Bundling and Minification in ASP.NET MVC