Data Annotation In MVC



In this post I want to show how to use Data Annotation Attribute in MVC.

What Is Data Annotation In MVC

Our web page must need validation. So in MVC we can use validation attribute by using Data Annotation to validate page.

Why Data Annotation

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users. This validation using both client side and server side validation. For server side validation we need to use ModelState.IsValid properties.

Overview of Data Annotation Attributes

DataType: Specify the datatype of a property

DisplayName: Specify the display name for a property.

DisplayFormat: Specify the display format for a property like different format for Date proerty.

Required: Specify a property as required.

ReqularExpression: Validate the value of a property by specified regular expression pattern.

Range: validate the value of a property with in a specified range of values.

StringLength: Specify min and max length for a string property.

MinimumLength: Specify minimum length for a string property.

MaxLength: Specify maximum length for a string property.

Url: To validate a url format.

Compare: To compare with the another field like Password and ConfirmPassword.

EmailAddress: Validate a email format.

Using Js and Css

    <link href="/Content/Site.css" rel="stylesheet" /> Download

    <script src="/Scripts/jquery-1.8.2.min.js"></script> Download
    <script src="/Scripts/jquery.validate.min.js"></script> Download
    <script src="/Scripts/jquery.validate.unobtrusive.min.js"></script> Download

Add Namespace

To use data annotation we need to add a namespace in the model class i.e. System.ComponentModel.DataAnnotations

If we want to use [DisplayName] attribute. We need to use an another namespace i.e. System.ComponentModel


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

namespace DataAnnotationMVC.Models
    public class Employee
        [DisplayName("First Name:")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "First Name should be between 3 and 50 characters!")]
        public string FirstName { get; set; }

        [DisplayName("Last Name:")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Last Name should be between 3 and 50 characters!")]
        public string LastName { get; set; }

        [EmailAddress(ErrorMessage = "Invalid Email")]
        public string Email { get; set; }

        [StringLength(500, ErrorMessage = "Address should be less than 500 characters!")]
        public string Address { get; set; }

        [Range(18, 100)]
        public int Age { get; set; }

        [DisplayName("Website URL:")]
        [Url(ErrorMessage = "Invalid URL!")]
        public string WebsiteUrl { get; set; }

        [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Invalid Phone Number, pattern should be [xxx-xxx-xxxx]!")]
        public string Phone { get; set; }

        [StringLength(15, MinimumLength = 8, ErrorMessage = "Passwords should be between 8 and 15 characters!")]
        [RegularExpression(@"((?=.*[a-z])(?=.*[A-Z])(?=.*\d)).+$", ErrorMessage = "Must contain one lower & uppercase letter, and one non-alpha character (a number or a symbol.)")]
        public string Password { get; set; }

        [Compare("Password", ErrorMessage = "Password and Confirmation Password Not Matched!")]
        public string ConfirmationPassword { get; set; }


@model DataAnnotationMVC.Models.Employee

    Layout = null;

<link href="/Content/Site.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm("Index", "AnnotationTest", FormMethod.Post))
    <div style="width: 60%; margin-left: 20%;margin-top:2%;">
        <h1>MVC Data Annotation</h1>
            <legend>Data Annotation</legend>
            <table style="margin-left: 20%;">
                        <td>@Html.LabelFor(s => s.FirstName)</td>
                        <td>@Html.TextBoxFor(s => s.FirstName)</td>
                        <td>@Html.ValidationMessageFor(s => s.FirstName)</td>
                        <td>@Html.LabelFor(s => s.LastName)</td>
                        <td>@Html.TextBoxFor(s => s.LastName)</td>
                        <td>@Html.ValidationMessageFor(s => s.LastName)</td>
                        <td>@Html.LabelFor(s => s.Email)</td>
                        <td>@Html.TextBoxFor(s => s.Email)</td>
                        <td>@Html.ValidationMessageFor(s => s.Email)</td>
                        <td>@Html.LabelFor(s => s.Address)</td>
                        <td>@Html.TextAreaFor(s => s.Address)</td>
                        <td>@Html.ValidationMessageFor(s => s.Address)</td>
                        <td>@Html.LabelFor(s => s.Age)</td>
                        <td>@Html.TextBoxFor(s => s.Age)</td>
                        <td>@Html.ValidationMessageFor(s => s.Age)</td>
                        <td>@Html.LabelFor(s => s.WebsiteUrl)</td>
                        <td>@Html.TextBoxFor(s => s.WebsiteUrl)</td>
                        <td>@Html.ValidationMessageFor(s => s.WebsiteUrl)</td>
                        <td>@Html.LabelFor(s => s.Phone)</td>
                        <td>@Html.TextBoxFor(s => s.Phone)</td>
                        <td>@Html.ValidationMessageFor(s => s.Phone)</td>
                        <td>@Html.LabelFor(s => s.Password)</td>
                        <td>@Html.PasswordFor(s => s.Password)</td>
                        <td>@Html.ValidationMessageFor(s => s.Password)</td>
                        <td>@Html.LabelFor(s => s.ConfirmationPassword)</td>
                        <td>@Html.PasswordFor(s => s.ConfirmationPassword)</td>
                        <td>@Html.ValidationMessageFor(s => s.ConfirmationPassword)</td>
                        <td colspan="2" style="text-align: center;">
                            <input type="submit" value="Submit" />
                    <tr><td colspan="2"><hr /></td></tr>


IF we want server side validation then use ModelState.IsValid properties.
using DataAnnotationMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DataAnnotationMVC.Controllers
    public class AnnotationTestController : Controller
        public ActionResult Index()
            return View();

        public ActionResult Index(Employee employee)
            if (ModelState.IsValid)
                ViewBag.Name = "Name: " + employee.FirstName + " " + employee.LastName;
                ViewBag.Email = "Email: " + employee.Email;
                ViewBag.Address = "Address: " + employee.Address;
                ViewBag.Age = "Age: " + employee.Age;
                ViewBag.WebsiteUrl = "WebsiteUrl: " + employee.WebsiteUrl;
                ViewBag.Phone = "Phone: " + employee.Phone;
                ViewBag.Password = "Password: " + employee.Password;
            return View();

Browser View

Using validation

After success validation

Using ValidationSummary


You can download this application zip file here


Guys I create this post to describe data annotation validation attribute. I hope this will helpful. If I missed something please leave a comment.

You Might Also Like