Data Annotation In MVC

15:06

Introduction

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

Model

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:")]
        [Required]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "First Name should be between 3 and 50 characters!")]
        public string FirstName { get; set; }

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

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

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

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

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

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

        [DisplayName("Password:")]
        [Required]
        [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.)")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

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

View

@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>
        <fieldset>
            <legend>Data Annotation</legend>
            <table style="margin-left: 20%;">
                <thead>
                    @Html.ValidationSummary()
                </thead>
                <tbody>
                    <tr>
                        <td>@Html.LabelFor(s => s.FirstName)</td>
                        <td>@Html.TextBoxFor(s => s.FirstName)</td>
                        <td>@Html.ValidationMessageFor(s => s.FirstName)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.LastName)</td>
                        <td>@Html.TextBoxFor(s => s.LastName)</td>
                        <td>@Html.ValidationMessageFor(s => s.LastName)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.Email)</td>
                        <td>@Html.TextBoxFor(s => s.Email)</td>
                        <td>@Html.ValidationMessageFor(s => s.Email)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.Address)</td>
                        <td>@Html.TextAreaFor(s => s.Address)</td>
                        <td>@Html.ValidationMessageFor(s => s.Address)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.Age)</td>
                        <td>@Html.TextBoxFor(s => s.Age)</td>
                        <td>@Html.ValidationMessageFor(s => s.Age)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.WebsiteUrl)</td>
                        <td>@Html.TextBoxFor(s => s.WebsiteUrl)</td>
                        <td>@Html.ValidationMessageFor(s => s.WebsiteUrl)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.Phone)</td>
                        <td>@Html.TextBoxFor(s => s.Phone)</td>
                        <td>@Html.ValidationMessageFor(s => s.Phone)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.Password)</td>
                        <td>@Html.PasswordFor(s => s.Password)</td>
                        <td>@Html.ValidationMessageFor(s => s.Password)</td>
                    </tr>
                    <tr>
                        <td>@Html.LabelFor(s => s.ConfirmationPassword)</td>
                        <td>@Html.PasswordFor(s => s.ConfirmationPassword)</td>
                        <td>@Html.ValidationMessageFor(s => s.ConfirmationPassword)</td>
                    </tr>
                    <tr><td>&nbsp;</td></tr>
                    <tr>
                        <td colspan="2" style="text-align: center;">
                            <input type="submit" value="Submit" />
                        </td>
                    </tr>
                    <tr><td>&nbsp;</td></tr>
                    <tr><td colspan="2"><hr /></td></tr>
                    <tr><td><label><b>Result:</b></label></td></tr>
                    <tr><td>@ViewBag.Name</td></tr>
                    <tr><td>@ViewBag.Email</td></tr>
                    <tr><td>@ViewBag.Address</td></tr>
                    <tr><td>@ViewBag.Age</td></tr>
                    <tr><td>@ViewBag.WebsiteUrl</td></tr>
                    <tr><td>@ViewBag.Phone</td></tr>
                    <tr><td>@ViewBag.Password</td></tr>
                </tbody>
            </table>
        </fieldset>
    </div>
}

Controller

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();
        }

        [HttpPost]
        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

Download

You can download this application zip file here

Conclusion

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

0 comments