Data Annotations and Validation in MVC Part Two

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.



We will see how we can implement our custom logic in data annotation attributes. If you are new in 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 address field in which address cannot accept more than 50 words.

Overview

For this article we create 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 in order 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. namespace DataAnnotationsValidations.Controllers  
  4. {  
  5.     public class StudentController: Controller  
  6.     {  
  7.         // GET: Student  
  8.         public ActionResult Index()  
  9.         {  
  10.             return View();  
  11.         }  
  12.         // GET: Student/Create  
  13.         public ActionResult Create()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         // POST: Student/Create  
  18.         [HttpPost]  
  19.         public ActionResult Create(StudentModel student)  
  20.         {  
  21.             try  
  22.             {  
  23.                 if (ModelState.IsValid)  
  24.                 {  
  25.                     return RedirectToAction("Index");  
  26.                 }  
  27.                 return View();  
  28.             }  
  29.             catch  
  30.             {  
  31.                 return View();  
  32.             }  
  33.         }  
  34.     }  
  35. }  
We have added a student view for Creating action method; when we run that view it will look like this.



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 to 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 framework also supports client side validation.

Custom Annotations

Imagine we want to restrict the address field value of a student to a limited number of words. For example we might say 50 words is more than enough for 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 application solution and added a class MaxWordAttributes class in it like this
  1. using System.ComponentModel.DataAnnotations;  
  2. namespace DataAnnotationsValidations.Attributes  
  3. {  
  4.     public class MaxWordAttributes: ValidationAttribute  
  5.     {}  
  6. }  
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 result, 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 constructor to accept 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!") we can see this is just a hardcoded error message. To write a good quality code we never want hardcoded error message. We always want to pass the error message and that error message should display instead 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): base("{0} has to many words.")  
  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.         if (textValue.Split(' ').Length <= _maxWords) return ValidationResult.Success;  
  13.         var errorMessage = FormatErrorMessage((validationContext.DisplayName));  
  14.         return new ValidationResult(errorMessage);  
  15.     }  
  16. }  
We made two changes in our above code.

 

  • First we place the default error message to the base constructor. 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 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 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 frameworkadds an additional Remote validation attribute. This attributes 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. Which is 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 should call. The client code will send the value the user enters for the UserName property automatically and an overload of the attributes constructor allows us to specify additional fields to send to the server.
  1. public JsonResult CheckUserName(string userName)  
  2. {  
  3.     var studentUserList = new List < string >  
  4.     {  
  5.         "Manish",  
  6.         "Saurabh",  
  7.         "Akansha",  
  8.         "Ekta",  
  9.         "Rakesh",  
  10.         "Bhayia Jee"  
  11.     };  
  12.     var result = studentUserList.Any(userName.Contains);  
  13.     return Json(result, JsonRequestBehavior.AllowGet);  
  14. }  
For example if user has hard coded 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 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 question or comments regarding this article, please post it in the comment section of this article. I hope you like it.

 


Similar Articles