Data Annotation in ASP.NET MVC

The model is the M in MVC. The data model represents the core business data/information that an application is being used to access and manipulate. The model is the center of any application. The model encapsulates the storage and validation concerns. HTML helpers are provided by ASP.NET MVC to do the input validations. Additionally, we can also use data annotation attributes from the System.ComponentModel.DataAnnotations namespace to do validations at the model level. Data annotation attributes are attached to the properties of the model class and enforce some validation criteria. They are capable of performing validation on the server side as well as on the client side. This article discusses the basics of using these attributes in an ASP.NET MVC application.

Create an empty MVC Project. Add two models as "EmployeeModel".

  1. public class EmployeeModel  
  2. {  
  3.     public int EmployeeId { getset; }  
  4.     public string FirstName { getset; }  
  5.     public string LastName { getset; }  
  6.     public string Email { getset; }  
  7.     public float Salary { getset; }  
  8.     public string PhoneNumber { getset; }  
  9.     public string AddressLine1 { getset; }  
  10.     public string AddressLine2 { getset; }  
  11.     public string PinCode { getset; }  
  12. }     

Add a controller "EmployeeController" with empty read/write.

EmployeeController

Add a Strongly Typed view for Create with the model as EmployeeModel.

add view

Change the "Create" action method with "HttpPost" attribute as:

  1. [HttpPost]  
  2. public ActionResult Create(EmployeeModel objEmp)  
  3. {  
  4.     try  
  5.     {  
  6.         if (ModelState.IsValid)  
  7.         { return Content("EmployeeModel is Valid.."); }  
  8.         else  
  9.         {  
  10.             return View(objEmp);  
  11.         }                 
  12.     }  
  13.     catch  
  14.     {  
  15.         return View(objEmp);  
  16.     }  
  17. }

Run the application. You will get a dialog with all the data items in EmployeeModel and click on Create. You will get a validation method as:

model as EmployeeModel

From this we can see that every non-nullable numeric field in a model is required. Now change the numeric field to nullable and run the application and click on "Create". This time you would not get any validation messages.

As I said, data annotation attributes are attached to the properties of the model class and enforce some validation criteria. There are several data annotations provide by MVC. Some frequently used tags are:

  • Required
  • Regular Expression
  • Range
  • EmailAddress
  • DisplayName
  • DisplayFormat
  • Scaffold
  • DataType
  • StringLength
  • UIHint
  • DataType
  • StringLength
  • MaxLength
  • MinLength

All in the preceding list have a self-descriptive name. I have changed the EmployeeModel and decorated it with annotation tags as in the following:

  1. [Required]  
  2. [ScaffoldColumn(false)]  
  3. public int EmployeeId { getset; }  
  4.   
  5. [DisplayName("First Name")]  
  6. [Required(ErrorMessage = "The First Name is required.")]  
  7. [MinLength(5, ErrorMessage = "The First Name must be atleast 5 characters")]  
  8. [MaxLength(15, ErrorMessage = "The First Name cannot be more than 15 characters")]  
  9. public string FirstName { getset; }  
  10.   
  11. [DisplayName("Last Name")]  
  12. [StringLength(15, MinimumLength = 5, ErrorMessage = "The Last Name should be between 5 to 15 characters")]  
  13. public string LastName { getset; }  
  14.   
  15. [Required(ErrorMessage = "The Email is required.")]  
  16. [EmailAddress(ErrorMessage = "Email is incorrect")]  
  17. public string Email { getset; }  
  18.   
  19. [DisplayName("Salary")]  
  20. [Required(ErrorMessage = "The Salary is required.")]  
  21. [Range(10000, 20000)]  
  22. [DisplayFormat(DataFormatString = "{0:#.####}")]  
  23. public float Salary { getset; }  
  24.   
  25. [Required(ErrorMessage = "Phone Number Required")]  
  26. [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Please enter PhoneNumber as 0123456789, 012-345-6789, (012)-345-6789.")]  
  27. public string PhoneNumber { getset; }  
  28.   
  29. [DataType(DataType.PostalCode)]  
  30. public string AddressLine1 { getset; }  
  31. public string AddressLine2 { getset; }  
  32.   
  33. [DataType(DataType.PostalCode)]  
  34. public string PinCode { getset; }

Now delete the View and re-add it. Now if you run the application then you will not find any field form "EmployeeId" as we set [ScaffoldColumn(false)].

If you click on "Create" with any invalid data you would get the validation error message for each field. If you want a summary for all error messages then we need to use:

  1. @Html.ValidationSummary(false

We can also remove the all "@Html.ValidationMessageFor()"and have only @Html.ValidationSummary(false).Default the color for validation message is Black that we can overwrite as:

  1. <style>  
  2.     .field-validation-error {  
  3.         color: red;  
  4.     }  
  5.   
  6.     .validation-summary-errors {  
  7.         font-weight: bold;  
  8.         color: red;  
  9.     }  
  10. </style> 

Now the output would be:

output

We can also check for business logic and add an error at action level. Consider the dummy business logic that "Email cannot be '[email protected]'". In that case we can validate the model data as:

  1. if (objEmp.Email == "[email protected]")  
  2. {  
  3.    ModelState.AddModelError("""Email can not be '[email protected]'");  

You can see that ModelState is valid before adding any error inside the action. As soon as we added any ModelError, modelState becomes invalid.

ModelState

And the output would be as in the following:

employee model

Up Next
    Ebook Download
    View all
    Learn
    View all