Validations In ASP.NET MVC 5.0: Part 13

Before reading this article, I highly recommend reading the previous parts of the series on ASP.NET:

Here are the following types of validation in ASP.NET MVC:

  • Client Side Validation
  • Server Side Validation

Client Side Validation:

I’ll discuss enabling client side validations and server side validations in ASP.NET MVC. For enabling client side validations, enable ClientValidation and UnobtrusiveJavaScript in Web.config file:

For client-side validation, the values of above shown both the keys must be true.

  1. <configuration>  
  2.     <appSettings>  
  3.         <add key="ClientValidationEnabled" value="true" />  
  4.         <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  5.     </appSettings>  
  6. </configuration>  
For enabling client side validation, we require including the jQuery min, validating & unobtrusive scripts in our view or layout page in the following order.
  1. <script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>  
  2. <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>  
  3. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>  
You can follow the below screenshot:

config

Now, I’m going to create Client Side Validations with the practical approach.

Step 1: Open the Visual Studio and select FILE, New, then Project.

new

project

As shown in the following figure select Templates, Visual C#, then ASP.NET Web Application, and here I have given the name of project “MVCValidationsDemo”.
  • You can give the project name as you wish.
  • And then click on “OK” button.

    web app

  • In the following figure as you can see the default MVC will be selected, select MVC and then click “OK” button.

    mvc

  • Firstly, I need to create a Models class, so right click on to Models folder and click on “Add” and then click on Class, to add a class.

    class


Select “class” from the menu, and give the proper name to your class, here I have given it “ClientSideValidation”.

Click on Add button.

add

So my Model class has been created, there is three properties in the class with the jQuery validation plug-in. I need to add “using System.ComponentModel.DataAnnotations;” namespace for the jQuery validation plug-in.

  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace MVCValidationsDemo.Models  
  4. {  
  5.     public class ClientSideValidation   
  6.     {  
  7.         [Required(ErrorMessage = "Enter your Name")]  
  8.         public string Name  
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.   
  14.         [Required(ErrorMessage = "Enter your Address")]  
  15.         public string Address  
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.   
  21.         [Required(ErrorMessage = "Enter your Email")]  
  22.   
  23.         [RegularExpression(@ "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  24.             @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  25.             @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",  
  26.             ErrorMessage = "Email is not valid")]  
  27.         public string Email  
  28.         {  
  29.             get;  
  30.             set;  
  31.         }  
  32.   
  33.     }  
  34. }  
You can see the following screenshot for your convenience:

code

Now, I need to create Controller, just right click on to Controllers folder and add a controller.

controller

After giving controller name, click on “Add” button.

add

Here, I’m using AcceptVerbs action filter because usage of HttpGet, HttpPost, HttpPut , are limited to only respective HTTP verb. I’m going to use AcceptVerbs action filter because sometimes you require that action method should be accessible by more than one HTTP verb, but not all.

Action method will be accessible by only HTTP GET & POST verbs.
  1. using MVCValidationsDemo.Models;  
  2.   
  3. namespace MVCValidationsDemo.Controllers  
  4. {  
  5.     public class ClientSideController: Controller  
  6.     {  
  7.         // GET: ClientSide  
  8.         public ActionResult Index()   
  9.         {  
  10.             return View();  
  11.         }  
  12.   
  13.         [AcceptVerbs(HttpVerbs.Post)]  
  14.         public ActionResult Index(ClientSideValidation model)  
  15.         {  
  16.             if (ModelState.IsValid)  
  17.             {  
  18.                 ViewBag.Name = model.Name;  
  19.                 ViewBag.Name = model.Name;  
  20.                 ViewBag.Email = model.Email;  
  21.             }  
  22.             return View(model);  
  23.         }  
  24.     }  
  25. }  
“ClientSideValidation” is my model class, I need to resolve it form the “using MVCValidationsDemo.Models; namespace.

controller

After this, now I need to add a view, right click near action method and add a view.

add view

View name should be Index, Template name should be “Create” and model class should be ClientSideValidation
(MVCValidationDemo.Models)”.

Check the “Reference script libraries” and “Use a layout page” because application automatically adds these references.

Click on “Add” button.

add view

Now client side validation is ready for use, save your application and run the project by pressing F5 key.

Call the respective controller that is “ClientSide”.

index

Name field is valid, Address field is empty and email is not valid in the following screenshot.

name

In the following screenshot Address and Email are valid but name field is required.

address

If all fields are valid then there is no validation message.

validation

Server Side Validation

Now, I’m going to use Server Side Validation in ASP.NET MVC using the Data Annotation API.

Server side validations ensure that the received data is correct and valid. If the received data is valid then we do further processing with the data. Server side validations are very important before playing with sensitive information of a user.

Server-side validation must be done whether we validate the received data on the client side. User could disable script in his browser or do something else to bypass client-side validation. In this case server-side validation must require to protect our data from dirty input.

In the ServerSideValidation named Model class, I have taken four properties, instead of three, rename the Model class and Controller to “ServerSideValidation” named:
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace MVCValidationsDemo.Models  
  4. {  
  5.     public class ServerSideValidation   
  6.     {  
  7.   
  8.         public string Name  
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         public string Address   
  14.         {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         public string Twitter   
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string Email   
  24.         {  
  25.             get;  
  26.             set;  
  27.         }  
  28.   
  29.     }  
  30. }  

code

Now, I’m going to make some changes in the Controller, my controller is ServerSideController.

ServerSideController

In the following code I have used [HttpPost]action method so that the method handles only HTTP POST requests.

I am using if (string.IsNullOrEmpty(model.Name))  to check if there name is empty, then message will be shown on the view whenever the data is not to be validated in the model, same for the other properties.

For the Email property I have used regular expression validation, if email does not not match with the expression it simply fire a validation that Email is not valid, otherwise enter valid email, if email format will be right then validation does not occur.

“Regx” is the class that will be resolved by “using System.Text.RegularExpressions;” namespace.
  1. using MVCValidationsDemo.Models;  
  2. using System.Text.RegularExpressions;  
  3.   
  4. namespace MVCValidationsDemo.Controllers  
  5. {  
  6.     public class ServerSideController: Controller   
  7.     {  
  8.         // GET: ServerSide  
  9.         public ActionResult Index()  
  10.         {  
  11.             return View();  
  12.         }  
  13.   
  14.         [HttpPost]  
  15.         publicActionResult Index(MVCValidationsDemo.Models.ServerSideValidation model)  
  16.         {  
  17.             if (string.IsNullOrEmpty(model.Name))  
  18.             {  
  19.                 ModelState.AddModelError("Name""Enter your Name");  
  20.             }  
  21.             if (string.IsNullOrEmpty(model.Address))  
  22.             {  
  23.                 ModelState.AddModelError("Address""Enter your Address");  
  24.             }  
  25.             if (string.IsNullOrEmpty(model.Twitter))  
  26.             {  
  27.                 ModelState.AddModelError("Twitter""Enter your twitter");  
  28.             }  
  29.   
  30.             if (!string.IsNullOrEmpty(model.Email))  
  31.             {  
  32.                 string emailRegex = @ "^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +  
  33.                     @ "\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +  
  34.                 @ ".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";  
  35.                 Regex re = newRegex(emailRegex);  
  36.                 if (!re.IsMatch(model.Email))  
  37.                 {  
  38.                     ModelState.AddModelError("Email""Email is not valid");  
  39.                 }  
  40.             } else  
  41.             {  
  42.                 ModelState.AddModelError("Email""Enter valid Email");  
  43.             }  
  44.             if (ModelState.IsValid)  
  45.             {  
  46.                 ViewBag.Name = model.Name;  
  47.                 ViewBag.Email = model.Address;  
  48.                 ViewBag.Name = model.Twitter;  
  49.                 ViewBag.Name = model.Email;  
  50.             }  
  51.             return View(model);  
  52.         }  
  53.     }  
  54. }  
See the following screenshot:

controller
Now, I need to add a view, right click on near action method and add a view.

view

View name should be Index, Template name should be “Create” and model class should be ServerSideValidation (MVCValidationDemo.Models)”.

Check the “Reference script libraries” and “Use a layout page” because application automatically adds these references.

Click on to “Add” button.

add

Now client side validation is ready for use, save your application and run the project by pressing F5 key.

Call the respective controller that is “ServerSide”. All fields are empty; you can check it one by one.

index

Click on to “Create” button, you will find all validations are working. Here's the screenshot:

create

 

I’ve entered wrong email, so it’s showing the error message,  “Email is not valid”.

email

In the following screenshot, all fields are correctly filled, there is no validation message.

message

Thanks for reading this article and stay tuned for next articles where you will learn a lot about ASP.NET MVC 5.0.

Connect(“Nitin Pandit);
 
Read more articles on ASP.NET:


Similar Articles