Custom Data Annotation Validation In MVC

Introduction

Validating user input has always been a challenging task for web developers. Not only do we want validation logic executing in the browser, but also we must validate the logic running on the server. The client-side logic gives users instant feedback on the information they entered into a web page and is an expected feature in today’s applications. Meanwhile, the server validation logic is in place because you should never trust information arriving from the network.
validation
In this article, we will see how custom validation logic works in data annotations in MVC framework. We will see how we can implement our custom logic in data annotation attributes. If you are new to data annotation validation please read my first article for built in data annotation validation.

In this article, we will try to implement our custom validation logic for the address field in which the address cannot accept more than 50 words.

Overview

For this article, we created an application ASP.NET MVC application name  DataAnnotationsValidations (you can download the source code for better understanding) and we are using Student Model Class that contains student relation information in which we are going to validate using Data Annotation.

  1. public class StudentModel    
  2. {    
  3.     public Guid StudentId { getset; }    
  4.     public string FirstName { getset; }    
  5.     public string LastName { getset; }    
  6.     public DateTime DateOfBirth { getset; }    
  7.     public string Address { getset; }    
  8.     public string ContactNo { getset; }    
  9.     public string EmailId { getset; }    
  10.     public string ConfirmEmail { getset; }    
  11.     public string UserName { getset; }    
  12.     public string  Password { getset; }    
  13. } 
We have added a student Controller and added Post action method to add new student. In this post action method, we will apply and test the data annotation validation.

Student Controller
  1. using System.Web.Mvc;  
  2. using DataAnnotationsValidations.Models;  
  3.   
  4. namespace DataAnnotationsValidations.Controllers  
  5. {  
  6.     public class StudentController : Controller  
  7.     {  
  8.         // GET: Student  
  9.         public ActionResult Index()  
  10.         {  
  11.             return View();  
  12.         }  
  13.   
  14.         // GET: Student/Create  
  15.         public ActionResult Create()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.         // POST: Student/Create  
  21.         [HttpPost]  
  22.         public ActionResult Create(StudentModel student)  
  23.         {  
  24.             try  
  25.             {  
  26.                 if (ModelState.IsValid)  
  27.                 {  
  28.   
  29.                     return RedirectToAction("Index");  
  30.                 }  
  31.                 return View();  
  32.             }  
  33.             catch  
  34.             {  
  35.                 return View();  
  36.             }  
  37.         }  
  38.   
  39.     }  
  40. }  
We have added a student view for Create action method when we run that view it will look like this.

output

Create Student View
  1. @model DataAnnotationsValidations.Models.StudentModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Add Student";  
  5. }  
  6.   
  7. <h3>Add New Student</h3>  
  8.   
  9. @using (Html.BeginForm())   
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.       
  13.     <div class="form-horizontal">  
  14.         <hr />  
  15.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })  
  18.             <div class="col-md-10">  
  19.                 @Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })  
  20.                 @Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })  
  21.             </div>  
  22.         </div>  
  23.   
  24.         <div class="form-group">  
  25.             @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
  26.             <div class="col-md-10">  
  27.                 @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
  28.                 @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
  29.             </div>  
  30.         </div>  
  31.   
  32.         <div class="form-group">  
  33.             @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
  34.             <div class="col-md-10">  
  35.                 @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
  36.                 @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
  37.             </div>  
  38.         </div>  
  39.   
  40.         <div class="form-group">  
  41.             @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })  
  42.             <div class="col-md-10">  
  43.                 @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })  
  44.                 @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })  
  45.             </div>  
  46.         </div>  
  47.   
  48.         <div class="form-group">  
  49.             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  50.             <div class="col-md-10">  
  51.                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  52.                 @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
  53.             </div>  
  54.         </div>  
  55.   
  56.         <div class="form-group">  
  57.             @Html.LabelFor(model => model.ContactNo, htmlAttributes: new { @class = "control-label col-md-2" })  
  58.             <div class="col-md-10">  
  59.                 @Html.EditorFor(model => model.ContactNo, new { htmlAttributes = new { @class = "form-control" } })  
  60.                 @Html.ValidationMessageFor(model => model.ContactNo, "", new { @class = "text-danger" })  
  61.             </div>  
  62.         </div>  
  63.   
  64.         <div class="form-group">  
  65.             @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
  66.             <div class="col-md-10">  
  67.                 @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })  
  68.                 @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })  
  69.             </div>  
  70.         </div>  
  71.   
  72.         <div class="form-group">  
  73.             @Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
  74.             <div class="col-md-10">  
  75.                 @Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { @class = "form-control" } })  
  76.                 @Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { @class = "text-danger" })  
  77.             </div>  
  78.         </div>  
  79.   
  80.         <div class="form-group">  
  81.             @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })  
  82.             <div class="col-md-10">  
  83.                 @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })  
  84.                 @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })  
  85.             </div>  
  86.         </div>  
  87.   
  88.         <div class="form-group">  
  89.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
  90.             <div class="col-md-10">  
  91.                 @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
  92.                 @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
  93.             </div>  
  94.         </div>  
  95.   
  96.         <div class="form-group">  
  97.             <div class="col-md-offset-2 col-md-10">  
  98.                 <input type="submit" value="Create" class="btn btn-danger" />  
  99.             </div>  
  100.         </div>  
  101.     </div>  
  102. }  
This is the initial set up we need to run this data annotation validation project. Now we are going the discuss the validation available in data annotation one by one.

Note

Data annotations are attributes we can find in the System.ComponentModel.DataAnnotations namespace. These attributes provide server-side validation and the framework also supports client-side validation.

Custom Annotations

Imagine we want to restrict the address field value of a student to limited number of words. For example, we might say 50 words is more than enough for an address field. You might also think that this type of validation (limiting a string to a maximum number of words) is something we can reuse with other modules in our application. If so, the validation logic is a candidate for packaging into reusable attributes.

So making the attributes reusable we are going to place all the custom annotation logic in one common place/folder, say Attributes, as we know all the validation annotations (such as Range, StringFormat ) ultimately derive from the ValidationAttribute base class. This base class is abstract and resides under System.ComponentModel.DataAnnotations namespace.

To keep validation logic in one place I have added an Attributes folder name in the application solution and added a class MaxWordAttributes class in it like this:
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace DataAnnotationsValidations.Attributes  
  4. {  
  5.     public class MaxWordAttributes : ValidationAttribute   
  6.     {  
  7.     }  
  8. }  
To implement the validation logic, we need to override one of the IsValid methods provided by the base class. Overriding the IsValid version takes ValidationContext as a parameter. The ValidationContext parameter gives us access to the model type, model object instance, and friendly display name of the property we are validating, among other pieces of information.
  1. public class MaxWordAttributes : ValidationAttribute     
  2. {    
  3.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)    
  4.     {    
  5.         return ValidationResult.Success;    
  6.     }    
  7. } 
The first parameter to the IsValid method is the value to validate. If the value is valid you can return successful validation results, but before we can determine whether the value is valid we need to know the count of the words in that field. So for that a programmer should pass how many values is too many for that property, to do that we need to create a constructer to accept a number of words.
  1. public class MaxWordAttributes : ValidationAttribute    
  2. {    
  3.     private readonly int _maxWords;    
  4.     public MaxWordAttributes(int maxWords)    
  5.     {    
  6.         _maxWords = maxWords;    
  7.     }    
  8.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)    
  9.     {    
  10.         return ValidationResult.Success;    
  11.     }    
  12. } 
Now we have parameterized the maximum word count so we can implement our validation logic and catch the validation error.
  1. public class MaxWordAttributes : ValidationAttribute    
  2. {    
  3.     private readonly int _maxWords;    
  4.     public MaxWordAttributes(int maxWords)    
  5.     {    
  6.         _maxWords = maxWords;    
  7.     }    
  8.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)    
  9.     {    
  10.         if (value == nullreturn ValidationResult.Success;    
  11.         var textValue = value.ToString();    
  12.         return textValue.Split(' ').Length > _maxWords     
  13.             ? new ValidationResult("Too long Address!")     
  14.             : ValidationResult.Success;    
  15.     }    
  16. } 
Here we just split the value and compare the count with maxWords. If it is greater than that it should return validation error message otherwise a successful result.

Here the problem with the last line new ValidationResult("Too long Address!") is we can see this is just a hardcoded error message. To write a good quality code we never want a hardcoded error message. We always want to pass the error message and that error message should display instated of this hardcoded one.

To do that we just need to change our code a bit.
  1. public class MaxWordAttributes : ValidationAttribute    
  2. {    
  3.     private readonly int _maxWords;    
  4.     public MaxWordAttributes(int maxWords)    
  5.         : base("{0} has to many words.")    
  6.     {    
  7.         _maxWords = maxWords;    
  8.     }    
  9.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)    
  10.     {    
  11.         if (value == nullreturn ValidationResult.Success;    
  12.         var textValue = value.ToString();    
  13.         if (textValue.Split(' ').Length <= _maxWords) return ValidationResult.Success;    
  14.         var errorMessage = FormatErrorMessage((validationContext.DisplayName));    
  15.         return new ValidationResult(errorMessage);    
  16.     }    
  17. } 
We made two changes to our above code. 
  • First we place the default error message to the base constructer. We should pull default error message from a resource file if we build an international stander application.

  • Second notice how the default error message includes a parameter placeholder ({0}). The placeholder exists because the second change, the call inherited FormatErrorMessage method, will automatically format the string using the display name property.

FormatErrorMessage ensures that we use a correct error message string even if the string is localized into a resource file. We can use our custom annotation attributes in the following ways.

  1. [DataType(DataType.MultilineText)]  
  2. [MaxWordAttributes(50)]  
  3. public string Address { getset; }  
In first use we will get default error message if validation failed and in the second use we will get the message that we set in our model.
  1. [DataType(DataType.MultilineText)]  
  2. [MaxWordAttributes(50,ErrorMessage="There are too many words in {0}.")]  
  3. public string Address { getset; }  
address

Remote

The ASP.NET MVC framework adds an additional Remote validation attribute. This attribute is in System.Web.Mvc namespace.

The Remote attributes enable us to perform client-side validation with server callback. Take for example the UserName property is of a StudentModel, We are not going to allow the user name that already exists in our database. This means to say for every student there must be a unique UserName. To achieve this we need to use Remote attributes.
  1. [Remote("CheckUserName","Student")]  
  2. public string UserName { getset; }   
Inside the attributes we can set the name of the action and the name of the controller the client call should call. The client code will send the value the user enters for the UserName property automatically and an overload of the attributes constructor allow us to specify additional fields to send to the server. 
  1. public JsonResult CheckUserName(string userName)    
  2. {    
  3.     var studentUserList = new List<string> {"Manish""Saurabh""Akansha""Ekta""Rakesh""Bhayia Jee"};    
  4.   
  5.     var result = studentUserList.Any(userName.Contains);    
  6.     return Json(result, JsonRequestBehavior.AllowGet);    
  7. }
For example, if we have a user hardcoded string list we can easily replace that string list with the value we get from database. When we run the application and try to enter the value that is inside the string list it will show validation failed error message.

Conclusion

In this article, we learned about the custom data annotation validation in ASP.Net MVC framework. If you have any questions or comments regarding this article, please post it in the comment section of this article. I hope you like it.


Similar Articles