ASP.Net MVC Server-Side Validation

This article explains the basics of ASP.NET MVC server-side validation using the Data Annotation API. The ASP.NET MVC Framework validates any data passed to the controller action that is executing, It populates a ModelState object with any validation failures that it finds and passes that object to the controller. Then the controller actions can query the ModelState to discover whether the request is valid and react accordingly.

I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState object and another uses the Data Annotation API to validate the model data.

Approach 1: Manually Add Error to ModelState object

I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following:

  1. namespace ServerValidation.Models  
  2. {  
  3.     public class User  
  4.     {  
  5.         public string Name { getset; }  
  6.         public string Email { getset; }          
  7.     }  
  8. }
After that I create a controller action in User Controller (UserController.cs under Controllers folder). That action method has logic for the required validation for Name and Email validation on the Email field. I add an error message on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the model.
  1. using System.Text.RegularExpressions;  
  2. using System.Web.Mvc;   
  3. namespace ServerValidation.Controllers  
  4. {  
  5.     public class UserController : Controller  
  6.     {          
  7.         public ActionResult Index()  
  8.         {              
  9.             return View();  
  10.         }  
  11.         [HttpPost]  
  12.         public ActionResult Index(ServerValidation.Models.User model)  
  13.         {  
  14.             if (string.IsNullOrEmpty(model.Name))  
  15.             {  
  16.                 ModelState.AddModelError("Name""Name is required");  
  17.             }  
  18.             if (!string.IsNullOrEmpty(model.Email))  
  19.             {  
  20.                 string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  21.                                          @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  22.                                             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";  
  23.                 Regex re = new Regex(emailRegex);  
  24.                 if (!re.IsMatch(model.Email))  
  25.                 {  
  26.                     ModelState.AddModelError("Email""Email is not valid");  
  27.                 }  
  28.             }  
  29.             else  
  30.             {  
  31.                 ModelState.AddModelError("Email""Email is required");  
  32.             }  
  33.             if (ModelState.IsValid)  
  34.             {  
  35.                 ViewBag.Name = model.Name;  
  36.                 ViewBag.Email = model.Email;  
  37.             }  
  38.             return View(model);  
  39.         }  
  40.     }  
  41. }
Thereafter I create a view (Index.cshtml) for the user input under the User folder.
  1. @model ServerValidation.Models.User  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }   
  5. @using (Html.BeginForm()) {   
  6.     if (@ViewData.ModelState.IsValid)  
  7.     {  
  8.         if(@ViewBag.Name != null)  
  9.         {  
  10.             <b>  
  11.                 Name : @ViewBag.Name<br />  
  12.                 Email : @ViewBag.Email  
  13.             </b>  
  14.         }  
  15.     }        
  16.     <fieldset>  
  17.         <legend>User</legend>   
  18.         <div class="editor-label">  
  19.             @Html.LabelFor(model => model.Name)  
  20.         </div>  
  21.         <div class="editor-field">  
  22.             @Html.EditorFor(model => model.Name)    
  23.             @if(!ViewData.ModelState.IsValid)   
  24.             {          
  25.                 <span class="field-validation-error">@ViewData.ModelState["Name"].Errors[0].ErrorMessage</span>   
  26.             }               
  27.         </div>   
  28.         <div class="editor-label">  
  29.             @Html.LabelFor(model => model.Email)  
  30.         </div>  
  31.         <div class="editor-field">  
  32.             @Html.EditorFor(model => model.Email)   
  33.             @if (!ViewData.ModelState.IsValid)   
  34.             {          
  35.                  <span class="field-validation-error">@ViewData.ModelState["Email"].Errors[0].ErrorMessage</span>   
  36.             }            
  37.         </div>  
  38.         <p>  
  39.             <input type="submit" value="Create" />  
  40.         </p>  
  41.     </fieldset>  
  42. }
Run the application and test in various ways
  1. When all fields are empty:

    image1.gif
    Figure 1.1: Validation Message when both fields are empty
     
  2. When the Name field is empty but Email is not valid:

    image2.gif
    Figure 1.2 : Validation Message when Email is not valid
     
  3. When both fields are valid:

    image3.gif
    Figure 1.3 All Fields are valid

Approach 2: Specifying Business Rules with Data Annotation

While the first approach works quite well, it does tend to break the application's separation of concerns. Namely, the controller should not contain business logic such as, the business logic belongs in the model.

Microsoft provides an effective and easy-to-use data validation API called Data Annotation in the core .NET Framework. It provides a set of attributes that we can apply to the data object class properties. These attributes offer a very declarative way to apply validation rules directly to a model.

First create a model named Student (Student.cs) under the Models folder and applies Data Annotation attributes on the properties of the Student class.

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace ServerValidation.Models  
  3. {  
  4.     public class Student  
  5.     {  
  6.         [Required(ErrorMessage = "Name is Requirde")]  
  7.         public string Name { getset; }  
  8.         [Required(ErrorMessage = "Email is Requirde")]  
  9.         [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  10.                             @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  11.                             @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",  
  12.                             ErrorMessage="Email is not valid")]  
  13.         public string Email { getset; }  
  14.     }  
  15. }
Now create an action method in the controller (StudentController class under the Controllers folder) that returns a view with a model after the post request.
  1. using System.Web.Mvc;  
  2. using ServerValidation.Models;  
  3. namespace ServerValidation.Controllers  
  4. {  
  5.     public class StudentController : Controller  
  6.     {  
  7.         public ActionResult Index()  
  8.         {  
  9.             return View();  
  10.         }  
  11.         [AcceptVerbs(HttpVerbs.Post)]  
  12.         public ActionResult Index(Student model)  
  13.         {  
  14.             if (ModelState.IsValid)  
  15.             {  
  16.                 ViewBag.Name = model.Name;  
  17.                 ViewBag.Email = model.Email;  
  18.             }  
  19.             return View(model);  
  20.         }  
  21.     }  
  22. }
After that I created a view (Index.cshtml) to get student details and show an error message if the model data is not valid.
  1. @model ServerValidation.Models.Student   
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.  @if (ViewData.ModelState.IsValid)  
  6.     {  
  7.         if(@ViewBag.Name != null)  
  8.         {  
  9.             <b>  
  10.                 Name : @ViewBag.Name<br />  
  11.                 Email : @ViewBag.Email  
  12.             </b>  
  13.         }  
  14.     }   
  15. @using (Html.BeginForm()) {  
  16.     @Html.ValidationSummary(true)   
  17.     <fieldset>  
  18.         <legend>Student</legend>   
  19.         <div class="editor-label">  
  20.             @Html.LabelFor(model => model.Name)  
  21.         </div>  
  22.         <div class="editor-field">  
  23.             @Html.EditorFor(model => model.Name)  
  24.             @Html.ValidationMessageFor(model => model.Name)  
  25.         </div>   
  26.         <div class="editor-label">  
  27.             @Html.LabelFor(model => model.Email)  
  28.         </div>  
  29.         <div class="editor-field">  
  30.             @Html.EditorFor(model => model.Email)  
  31.             @Html.ValidationMessageFor(model => model.Email)  
  32.         </div>   
  33.         <p>  
  34.             <input type="submit" value="Create" />  
  35.         </p>  
  36.     </fieldset>  
  37. }
Let's run the application and perform the same test case as performed in the first approach. We will then get the same results.

 


Similar Articles