Data Annotations in ASP.NET MVC Application

Data Annotation is one of the best approach to implement validation in ASP.Net MVC application. It’s depends on System.ComponentModel.DataAnnotations assembly and Data Annotation has a set of attributes and classes.

public class EmployeeVM{

 [Required(ErrorMessage = "The ID is required.")] 
 public int Id { get; set; } 

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

 [Range(1, 200, ErrorMessage = "A number between 1 and 200.")]
 public int Age { get; set; } 

 [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",  ErrorMessage = "Invalid phone number.")] 
 public string Phone { get; set; } 

 [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Invalid email address.")] 
 public string Email { get; set; } 

Data Annotation 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 with in 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.


[Bind(Exclude = "EmployeeID")]
public class Employee
public int EmployeeId { get; set; }
 [DisplayName("Employee Name")]
[Required(ErrorMessage = "The name is required.")]
 public string Name { get; set; } 
 [Required(ErrorMessage = "Address is required")] 
 public string Address { get; set; } 
 [Required(ErrorMessage = "Price is required")]
 [Range(5000.00, 50000.00,  ErrorMessage = "Price must be between 5000.00 and 50000.00")] 
 public decimal Salary { get; set; } 


Leave a Reply

Your email address will not be published. Required fields are marked *