Data Annotation Validation with Example in ASP.NET MVC

In this chapter, you will learn:
1. What is Data Annotation in ASP.NET MVC?
2. Client Side Validation in MVC
3. How to apply client side validation in ASP.NET MVC using Data Annotation

What is Data Annotation?

Validating user input is not only necessary but it is compulsory these days. Data Annotation provides instant user input checking facility at client side and provides to asp developer, a wide range of validator attributes. Data Annotation makes the validating process easy and quick.

Data Annotation attributes directly applies to Model class member and those members are bounded to accept valid user input according to Data Annotation Rule.

Data Annotation can be used after adding following namespace.

System.ComponentModel.DataAnnotations using System.ComponentModel;

Data Annotation Attributes

Here, is a list of some important Data Annotation Attributes.

1. Required
Specifies that Input field cannot be empty.
Example:

[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }

2. DisplayName
Specifies the Display Name for a Property.
Example:
[DisplayName("Enter Your Name: ")]
public string Name { get; set; }

3. StringLength
Specifies minimum and maximum length for a property.
Example:
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }

4. Range
Specifies a range of numeric value.
Example:
[Range(1,120, ErrorMessage ="Age must be between 1-120 in years.")]        
public int Age { get; set; }

5. Bind
Include or Exclude value when adding form values to model properties.
Example:
[Bind(Exclude = "Id")]

6. ScaffoldColumn
Specifies a field for hiding from editor forms.
Example:
[ScaffoldColumn(false)]
public int Id { get; set; }

7. DisplayFormat
Specifies a display format for a property like Date Format, Currency format etc.
Example:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public System.DateTime? HireDate { get; set; }

8. ReadOnly
It set a property to read-only.
Example:
[ReadOnly(true)]
public string Name { get; private set; }

9. MaxLength
Specifies max length of string.
Example:

[MaxLength(50)]
public string Name { get; set; }

10. CreditCard
specifies that a data field value is credit card number.
Example:

[DataType(DataType.CreditCard)]
public string Name { get; set; }

11. Compare
compare with other input fields.
Example:
[System.ComponentModel.DataAnnotations.Compare("Email", ErrorMessage = "Email Not Matched")]
public string ConfirmEmail { get; set; }

12. EmailAddress
specifies that an input field value is well-formed Email Address using Regular Expression.
Example:
[Required(ErrorMessage = "Email ID is Required")]
[DataType(DataType.EmailAddress)]
[MaxLength(50)]
[RegularExpression(@ "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Email { get; set;}

13. Phone
specifies that an input field value is well-formed phone number using Regular Expression.
Example:
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{2})[-. ]?([0-9]{4})[-. ]?([0-9]{3})[-. ]?([0-9]{3})$", ErrorMessage = "Not a valid Phone number")]
public string Name { get; set; }

Output format: 91-1234-567-890
14. Url
specifies URL validation.
Example:
[Url][Required]
public string URL { get; set; }

15. RegularExpression
specifies that input field is matched with desired Regular Expression.
Example:
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Email { get; set; }

16. DataType
provides a list of data type that is associated with input field and parameter.
Example:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }

17. HiddenInput
specifies a hidden input field.
Example:
[System.Web.Mvc.HiddenInput(DisplayValue = false)]
public string Name { get; set; }

 

Complete Programming Example

Let’s understand all these with complete programming example.

Step 1: Create StudentModel.cs

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

namespace FormValidation.Models
{
    [Bind(Exclude = "Id")]   
    public class StudentModel
    {
        [ScaffoldColumn(false)]
        public int Id { get; set; }

        [Required(ErrorMessage = "Name is Required")]
        [StringLength(50,MinimumLength =3)]
        public string Name { get; set; }

        [Required(ErrorMessage ="Email ID is Required")]
        [DataType(DataType.EmailAddress)]
        [MaxLength(50)]
        [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
        public string Email { get; set; }
                
        [Required(ErrorMessage ="Confirm Email is Required")]
        [DataType(DataType.EmailAddress)]
        [System.ComponentModel.DataAnnotations.Compare("Email", ErrorMessage = "Email Not Matched")]
        public string ConfirmEmail { get; set; }

        [Required(ErrorMessage ="Age is Required")]
        [Range(1,120, ErrorMessage ="Age must be between 1-120 in years.")]        
        public int Age { get; set; }
    }
}

Step 2: Create a form in Index.cshtml page.

@{
    ViewBag.Title = "Home Page - Student Details";
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
@model FormValidation.Models.StudentModel
<h2>Student Details</h2>
@using (Html.BeginForm("StudentDetails", "Home", FormMethod.Post))
{
    <ol>
        <li>
            @Html.LabelFor(m => m.Name)
            @Html.TextBoxFor(m => m.Name)
            @Html.ValidationMessageFor(m => m.Name)
        </li>  
        <li>
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </li>     
        <li>
            @Html.LabelFor(m => m.ConfirmEmail)
            @Html.TextBoxFor(m => m.ConfirmEmail)
            @Html.ValidationMessageFor(m => m.ConfirmEmail)
        </li>
        <li>
            @Html.LabelFor(m => m.Age)
            @Html.TextBoxFor(m => m.Age)
            @Html.ValidationMessageFor(m => m.Age)
        </li>
    </ol>
    <input type="submit" value="Save Student Details" />
}

<h3 style="color:green">Student Details</h3>
<h4 style="color:green">
    <b>Name: @ViewBag.name<br />
       Email: @ViewBag.email<br />
       Age: @ViewBag.age</b>
</h4>

Step 3: Add following code in HomeController.cs

[HttpPost]
public ActionResult StudentDetails(StudentModel sm)
{
 if (ModelState.IsValid)
 {
  ViewBag.name = sm.Name;
  ViewBag.email = sm.Email;
  ViewBag.age = sm.Age;
  return View("Index");
 }
 else
 {
  ViewBag.name = "No Data";
  ViewBag.email = "No Data";
  ViewBag.age = "No Data";
  return View("Index");
 }
}

Output Image
Let's understand this code:

1. I have added several data annotation attributes to model properly.



[Required(ErrorMessage = "Name is Required")]
[StringLength(50,MinimumLength =3)]
 public string Name { get; set; }

2. Creation of form is same and nothing changed.

Custom Validation using Data Annotation

Till now, you learned how to use predefined Data Annotation attribute to validate input field. But, what is the way of adding a custom rule in data annotation? Here, I will explain how can, you add your own custom validation rule to Data Annotation.

For example, you want to create a custom attribute MinAgeAttribute(), in which user is forced to enter their age 18 or more than 18. This is just an example and after knowing that method of adding a custom attribute in data annotation, you can feed your own rules.

Step 1: Create a separate folder CustomAttribute in your project. Create a class MinAgeAttribute.cs in this folder.
Custom Attribute
Step 2: Add the following code in MinAgeAttribute.cs class

using System.ComponentModel.DataAnnotations;

namespace FormValidation.CustomAttribute
{
    public class MinAgeAttribute : ValidationAttribute
    {
        private int _minAge;
        public MinAgeAttribute(int value)
        {
            _minAge = value;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if(value!=null)
            {
                if(value is int)
                {
                    int minimumage = (int)value;
                    if(minimumage < _minAge)
                    {
                        return new ValidationResult("Minimum age must be " + _minAge);
                    }
                }
            }
            return ValidationResult.Success;
        }
    }
}

Let’s understand this code

Understand Custom Validation

Created MinAgeAttribute class derived from ValidationAttribute class. You must add a namespace using System.ComponentModel.DataAnnotations; in order to use ValidationAttribute class.

1. public class MinAgeAttribute : ValidationAttribute
2. Override IsValid method in order to push own custom logic.
3. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
Step 3: Now, use this attribute as like:

[Required(ErrorMessage ="Age is Required")]
[FormValidation.CustomAttribute.MinAge(18)]     
public int Age { get; set; }

Custom Validation Output

Summary

In this chapter, I explained how to use Data Annotation for validating input field in ASP.NET MVC 5. I also explained how to add custom validation rule in DataAnnotation. In the next chapter, you will learn Remote Validation in ASP.NET MVC. Remote Validation checks user input field instantly when the focus jumps out from input control.

 

Share your thought