How to add Data annotation validation in ASP.NET MVC

Updated on     Kisan Patel

First of all You need to know which namespace or Reference is for DataAnnotation validation in MVC :

using System.ComponentModel.DataAnnotations;

This namespace is already Built-in .NET Framework

Here are some Validation Attributes :

Required, Range, StringLength, RegularExpression, DataType, EmailAddress, Currency, MinLength, MaxLength etc.

Required :

You can use this attribute as

[Required]
[Required(ErrorMessage = "Your Message for Required Field")]

Range :

You can use this attribute as

[Range(1,10 , ErrorMessage = "value must be between 1 to 10")]

StringLength :

You can use this attribute as

[StringLength(5)]

RegularExpression :

You can use this attribute as

[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered Contact No format is not valid.")]

DataType :

You can use this attribute as

[DataType(DataType.EmailAddress, ErrorMessage = "Error message.")]

Now take a look at an Example

Example :

public class Profile
{
 [Key]
 public int Id { get; set; }
 
 [Required(ErrorMessage = "First Name is Required")]
 [Display(Name = "FirstName")]
 public string FirstName { get; set; }
 
 [Required(ErrorMessage = "Email ID is Required")]
 [DataType(DataType.EmailAddress, ErrorMessage = "Email ID is not valid.")]
 [Display(Name = "Email Id")]
 public string EmailId { get; set; }
 
 [Required(ErrorMessage = "Contact No is Required")]
 [Display(Name = "Contact No")]
 [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered Contact No format is not valid.")]
 public string ContactNo { get; set; }
 
 [StringLength(5)]
 [Required(ErrorMessage = "Rating is Required")]
 public string Rating { get; set; }
 
 [Required(ErrorMessage = "Age is Required")]
 [Range(1, 100, ErrorMessage = "Age must be between $1 and $100")]
 public decimal Age { get; set; }
}

Now model Profile is created so now how to use it for validation purpose.

Controller page :

[HttpPost]
public ActionResult Create(Profile model)
{
 // and if You want to remove validation for field Id then
 if (ModelState.Keys.Contains("Id"))
 {
 ModelState["Id"].Errors.Clear();
 }
 if (ModelState.IsValid) //this condition is for validation checking on server side
 {
 dbContext.Profile.Add(model);
 dbContext.SaveChanges();
 return RedirectToAction("ProfileList");
 }
 return View(model);
}

Next, in view you can do client-side Validation using JS of jquery which are “jquery.validate.min.js” and “jquery.validate.unobtrusive.min.js”
so add this jQuery in Header (</head>) tag and write this code

@model Mvc.Models.Profile
@{
   ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
   @Html.ValidationSummary(true)
   <fieldset>
        <legend>Movie</legend>
             <div class="editor-label">
                  @Html.LabelFor(model => model.FirstName)
             </div>
             <div class="editor-field">
                  @Html.EditorFor(model => model.FirstName)
                  @Html.ValidationMessageFor(model => model.FirstName)
             </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>
             <div class="editor-label">
                  @Html.LabelFor(model => model.ContactNo)
             </div>
             <div class="editor-field">
                  @Html.EditorFor(model => model.ContactNo)
                  @Html.ValidationMessageFor(model => model.ContactNo)
             </div>
             <div class="editor-label">
                  @Html.LabelFor(model => model.Rating)
             </div>
             <div class="editor-field">
                  @Html.EditorFor(model => model.Rating)
                  @Html.ValidationMessageFor(model => model.Rating)
            </div>
            <div class="editor-label">
                  @Html.LabelFor(model => model.Age)
            </div>
            <div class="editor-field">
                  @Html.EditorFor(model => model.Age)
                  @Html.ValidationMessageFor(model => model.Age)
            </div>
     <p>
           <input type="submit" value="Submit" class="btn btn-success" />
     </p>
 </fieldset>
}

Now, your coding is done Test your code.

Validation

 

Download Complete Source Code


ASP.NET MVC

Leave a Reply