Validation Using Data Annotations In MVC

Introduction

I am a beginner in MVC. I don't have knowledge regarding MVC but I am keen to learn this new framework. In this article, we will create a form in MVC and wilI add validation through the use of Data Annotations. Thus, let's start.
 
Description

Create a new Web project and add MVC Web template without authentication. You will see some already build in controller and view in the Application. If you run the Application, you will see the Web Pages of Home, About, Contact etc. in the application. We are here to implement validation, using Data Annotations, which we can implement on any model, so our first requirement is to create a model in which we declare all the properties we require in our form. Right click on Model and add new class with the name clsMembers or anything you want, according to your need and add properties you want in this.Take a look on the code, given below, for the properties I made in the Members class.
 
clsMembers.cs 
 

You can see in the image, shown above, I created a class in the Model folder and declared the properties in it. You will see above each property I have defined or called;  some properties like Required, StringLenght, DataType etc. All these are the attributes from the class Data Annotations.
 
You will  add the attribute you want above each property, according to your need. For example, I want all these fields as required, so I write the attribute [Required(ErrorMessage="")] and then the error message I want to show with the property. This is what you have to do with all the properties and you can add other attributes. For example, you can see on the email password,  and we have other attribute also. You can Google about these attributes or can even search here on C Sharp Corner. Thus, our first step is done.

Now, we will create a Controller and will add a view from the controller.

 

Add a controller with the name Account and create an Action Result with the name Register like the code, given below:
  1. public class AccountController : Controller  
  2. {  
  3.    // GET: Account  
  4.     public ActionResult Register()  
  5.     {  
  6.        return View();  
  7.     }  
  8. }  
Now, right click on the ActionResult Register and add view with the same name. After adding view, it's time to create the form. 
  1. @model MVCDemo.Models.clsMembers    
  2. @{    
  3.     ViewBag.Title = "Register";    
  4. }    
  5.     <style type="text/css">    
  6.         .field-validation-error {    
  7.             color: #ff0000;    
  8.         }    
  9.     
  10.         .field-validation-valid {    
  11.             display: none;    
  12.         }    
  13.     
  14.         .input-validation-error {    
  15.             border: 1px solid #ff0000;    
  16.             background-color: #ffeeee;    
  17.         }    
  18. </style>    
  19. <script src="~/Scripts/jquery-1.10.2.min.js"></script>    
  20. <script src="~/Scripts/jquery.validate.js"></script>    
  21. <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>  
  22. <h2>Register</h2>    
  23. <div style="margin:auto;width:50%;">    
  24.     @using (@Html.BeginForm("Register", "Account", FormMethod.Post, new { id = "frmRegister" }))    
  25.     {    
  26.         <table>    
  27.             <tr>    
  28.                 <td>    
  29.                      @Html.Label("Firstname")    
  30.                 </td>    
  31.                 <td>    
  32.                     @Html.TextBoxFor(m => m.FirstName, new { placeholder = "Firstname" })    
  33.                 </td>    
  34.                 <td>    
  35.                     @Html.ValidationMessageFor(m => m.FirstName)    
  36.                 </td>    
  37.             </tr>    
  38.             <tr>    
  39.                 <td>    
  40.                     @Html.Label("Lastname")    
  41.                 </td>    
  42.                 <td>    
  43.                     @Html.TextBoxFor(m => m.LastName, new { placeholder = "Lastname" })    
  44.                 </td>    
  45.                 <td>    
  46.                     @Html.ValidationMessageFor(m => m.LastName)    
  47.                 </td>    
  48.             </tr>    
  49.             <tr>    
  50.                 <td>    
  51.                     @Html.Label("Department")    
  52.                 </td>    
  53.                 <td>    
  54.                     @Html.TextBoxFor(m => m.Department, new { placeholder = "Department" })    
  55.                 </td>    
  56.                 <td>    
  57.                     @Html.ValidationMessageFor(m => m.Department)    
  58.                 </td>    
  59.             </tr>    
  60.             <tr>    
  61.                 <td>    
  62.                     @Html.Label("Username")    
  63.                 </td>    
  64.                 <td>    
  65.                     @Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })    
  66.                 </td>    
  67.                 <td>    
  68.                     @Html.ValidationMessageFor(m => m.Username)    
  69.                 </td>    
  70.             </tr>    
  71.             <tr>    
  72.                 <td>    
  73.                     @Html.Label("Password")    
  74.                 </td>    
  75.                 <td>    
  76.                     @Html.TextBoxFor(m => m.Password, new { type = "password"placeholder = "Password" })    
  77.                 </td>    
  78.                 <td>    
  79.                     @Html.ValidationMessageFor(m => m.Password)    
  80.                 </td>    
  81.             </tr>    
  82.             <tr>    
  83.                 <td>    
  84.                     @Html.Label("ConfirmPassword")    
  85.                 </td>    
  86.                 <td>    
  87.                     @Html.TextBoxFor(m => m.ConfirmPassword, new { type = "password"placeholder = "ConfirmPassword" })    
  88.                 </td>    
  89.                 <td>    
  90.                     @Html.ValidationMessageFor(m => m.ConfirmPassword)    
  91.                 </td>    
  92.             </tr>    
  93.             <tr>    
  94.                 <td>    
  95.                     @Html.Label("Email")    
  96.                 </td>    
  97.                 <td>    
  98.                     @Html.TextBoxFor(m => m.Email, new { placeholder = "Email Address" })    
  99.                 </td>    
  100.                 <td>    
  101.                     @Html.ValidationMessageFor(m => m.Email)    
  102.                 </td>    
  103.             </tr>    
  104.             <tr>    
  105.                 <td></td>    
  106.                 <td  style="text-align:center;">    
  107.                     <input type="submit" value="Submit" />    
  108.                 </td>    
  109.                 <td></td>    
  110.             </tr>    
  111.         </table>    
  112.         }    
  113. </div>    
In the view (Register), we will create the form now. In the code, given above, check the first line in which we get the reference of Member class so that we can access to the properties of the class. Afterwards, we create the form, using HTML Helper class. Thus, everything is done for now. We just need JavaScript file to run the validation on submit click, if we want to validate this on the client side.

You can see the code, given above. We give the reference of three JavaScript files in the page. They will work with the Data Annotations, if you don't give the reference of these files, your validation will not work (Client Side). Hence, we will add the reference and then everything is done. Now, it's time to run the code, just hit F5 to see the output and you will see the output, as shown below: 

If you hit the submit button, you will get the validation message, as shown in the image, given above. This is a client side validation, using Data Annotations. Now, lets do the Server side validation with Data Annotations. Comment on the Script files on the register page.



Now, if you see in the code, given above, where we are creating forms with the help of HTML Helper class, we write the action name and the controller name, where this action exists and the method type.

 
 
Thus, now we already having a Registered Action in the Account Controller and here we are again giving the action with the same name --  then what will happen? We will create an action result type of Post with the name Register, it will pass the model in it and will chec if the model state is valid or not. 
  1.         [HttpPost]  
  2.         public ActionResult Register(clsMembers objMembers)  
  3.         {  
  4.             if (ModelState.IsValid)  
  5.             {  
  6.                 return View("Completed");  
  7.             }  
  8.             else  
  9.             {  
  10.                 return View();  
  11.             }  
  12.         }  
If you see in the code given above, we created an action with the name Register and passed the Model in it. Afterwards, wewill check if the Model State is valid or not; if it's valid, then we can save the data in the database( I haven't written code for it), or if not, then empty view will return and it will automatically invoke the Data Annotations validation. Our Server side validation is done. If you still run the code, hit on Submit and make a breakpoint out here on action. You will clearly understand the validation is running from the Server side.

That's it for now. Hope this will be helpful for newcomers in MVC like me.