Validations in ASP.NET MVC application

There are various validations that are used in ASP.NET MVC application .Among them Data Annotation Validators is one of the beneficial validator that can be used in ASP.NET MVC application to apply validations .To use this tool user must have Data Annotations Model Binder but  Data Annotations Model Binder is not an official part of the Microsoft ASP.NET MVC framework .

Advantage of  using Data Annotation Validators :
It helps the user to perform validation simply by adding attribute directly to a Class Property like to perform validation on any string to bound its length than just use a simple attribute StingLenght to do so.

Data Annotation Validators Attribute are:

  • Range – To check weather a value of property falls under the specified range of values.
  • ReqularExpression – To check  whether the value of a property matches a specified regular expression pattern.
  • Required –It enables the user to  mark a property as required.
  • StringLength – It helps the user to  specify a maximum length for a string property.
  • Validation – It is the  class for all validator attributes.

Sample Code to show the use of  Data Annotaion Validators

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcApplication3.Models
{
 public class Product       
{
public int Id { get; set;
   [Required]
   [StringLength(20)]
public
string Name { get; set;
   [Required]
public
string Type { get; set;
   [DisplayName("Cost")]
   [Required]
[RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
public
decimal Cost { get; set; }
}
}

In the above example validation are applied on  Name, Type  and Cost  properties are checked as per requirement . As Name property is restricted with the string length or the number of characters must be less than 20.And the Cost property must match a regular expression pattern that are specified by the user.