Monday, 19 November 2012

MVC Data Annotations for Model Validation


What are data annotations?

Data annotations are attribute classes that live in the System.ComponentModel.DataAnnotations namespace that you can use to apply to (decorate) classes or properties to enforce pre-defined validation rules.

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes:

1. DataType: Specify the datatype of a property
2. DisplayName: Specify the display name for a property.
3. DisplayFormat:  Specify the display format for a property like different format for Date proerty.
4. Required: Specify a property as required.
5. ReqularExpression: Validate the value of a property by specified regular expression pattern.
6. Range: Validate the value of a property within a specified range of values.
7. StringLength: Specify min and max length for a string property.
8. MaxLength: Specify max length for a string property.
9. Bind: Specify fields to include or exclude when adding parameter or form values to model properties.
10. ScaffoldColumn: Specify fields for hiding from editor forms.

Designing the model with Data Annotations:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Employee.Models
{
    [Bind(Exclude = "AlbumId")]
    public class Employee
    {
        [ScaffoldColumn(false)]
        public int EmpId { get; set; }

        [DisplayName("Employee Name")]
        [Required(ErrorMessage = "Employee Name is required")]
        [StringLength(100, MinimumLength = 3)]
        public String EmpName { get; set; }

        [Required(ErrorMessage = "Employee Address is required")]
        [StringLength(300)]
        public string Address { get; set; }

        [Required(ErrorMessage = "Salary is required")]
        [Range(3000, 10000000, ErrorMessage = "Salary must be between 3000 and 10000000")]
        public int Salary { get; set; }

        [Required(ErrorMessage = "Please enter your 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 Email { get; set; }
    }
}

Once we have defined validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


Presenting the model in the view:

@model Employee.Models
@{
    ViewBag.Title = "Employee Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
    <div class="editor-label">
        @Html.LabelFor(m => m.EmpName)
    </div>
   
    <div class="editor-field">
        @Html.TextBoxFor(m => m.EmpName) @Html.ValidationMessageFor(m => m.EmpName)
    </div>
   
    <div class="editor-label">
        @Html.LabelFor(m => m.Address)
    </div>
   
    <div class="editor-field">
        @Html.TextBoxFor(m => m.Address) @Html.ValidationMessageFor(m => m.Address)
    </div>
   
    <div class="editor-label">
        @Html.LabelFor(m => m.Salary)
    </div>
   
    <div class="editor-field">
        @Html.TextBoxFor(m => m.Salary) @Html.ValidationMessageFor(m => m.Salary)
    </div>
   
    <div class="editor-label">
        @Html.LabelFor(m => m.Email)
    </div>
   
    <div class="editor-field">
        @Html.TextBoxFor(m => m.Email) @Html.ValidationMessageFor(m => m.Email)
    </div>
   
    <p>
        <input type="submit" value="Save" />
    </p>
}

1 comment: