ASP.NET MVC 5 - JQuery Form Validator

ASP.NET

Form Component is an important portion on any website that requires data input from the end-user. It could be an account creation form, feedback form, or any kind of information registration form etc. Since the data required on forms is input by end-users, it is the responsibility of a web engineer to ensure the kind of information the end-user is allowed to register. So, here comes Web Form Validation into play.

Web form validation is of two types i.e.

  1. Client-side form validation
  2. Server-side form validation

Client-Side Form Validation

This type of form validation is done at browser level, i.e., handling simple constraint validations; e.g. - checking empty input fields, identifying valid email address, verification of password constraints etc. Client side form validation also helps in providing better user interactivity with the website, while deep verification or validation of input data is being done at Server-side.

Server-Side Form Validation

Server side form validation, as the name suggests, is done on the Server side of the web which involves deep validation and verification on user input data, e.g. identification of valid user account etc.

Today, I shall be demonstrating the integration of jQuery based Client-side Validator with ASP.NET MVC5 platform. Although, MVC 5 platform already facilitates client side validation as a built-in component, yet the built-in client side validator component is not very user attractive or rich in nature.

Following are some prerequisites before you proceed further in this article.

  1. Knowledge of ASP.NET MVC5.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of Jquery.
  6. Knowledge of C# Programming.

You can download the complete source code for this article or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Now, let’s begin.

Create a new MVC web project and name it as "JqueryFormValidator".

Make sure that you have installed the following two JavaScripts into your "Scripts" folder i.e.

  1. jquery.validate.js
  2. jquery.validate.unobtrusive.js
ASP.NET

Now, open "RouteConfig.cs" file and replace the following code in it i.e.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace JqueryFormValidator  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Home", action = "Register", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  

In the above code, I have simply changed my default launch action from "Index" to "Register".

Now, open "BundleConfig.cs" file and replace it with the following code.

  1. using System.Web;  
  2. using System.Web.Optimization;  
  3.   
  4. namespace JqueryFormValidator  
  5. {  
  6.     public class BundleConfig  
  7.     {  
  8.         // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862  
  9.         public static void RegisterBundles(BundleCollection bundles)  
  10.         {  
  11.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  12.                         "~/Scripts/jquery-{version}.js"));  
  13.   
  14.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  15.                         "~/Scripts/jquery.validate.js",  
  16.                         "~/Scripts/jquery.validate.unobtrusive.js"));  
  17.   
  18.             // Use the development version of Modernizr to develop with and learn from. Then, when you're  
  19.             // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
  20.             bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
  21.                         "~/Scripts/modernizr-*"));  
  22.   
  23.             bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(  
  24.                       "~/Scripts/bootstrap.js",  
  25.                       "~/Scripts/respond.js"));  
  26.   
  27.             // JQuery validator.   
  28.             bundles.Add(new ScriptBundle("~/bundles/custom-validator").Include(  
  29.                                   "~/Scripts/script-custom-validator.js"));  
  30.   
  31.             bundles.Add(new StyleBundle("~/Content/css").Include(  
  32.                       "~/Content/bootstrap.css",  
  33.                       "~/Content/site.css"));  
  34.         }  
  35.     }  

In the above code, I have added my "jquery.validate.js", "jquery.validate.unobtrusive.js" & "script-custom-validator.js" scripts as a bundle, which are required for jQuery form validation. Following lines of code are added in above code.
  1. bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  2.                         "~/Scripts/jquery.validate.js",  
  3.                         "~/Scripts/jquery.validate.unobtrusive.js"));  
  4.   
  5.   
  6.            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(  
  7.                       "~/Scripts/bootstrap.js",  
  8.                       "~/Scripts/respond.js")); 

Create a new Controller class in "Controllers" folder and name it "HomeController.cs". Replace the following code in "HomeController.cs" file.

  1. using JqueryFormValidator.Models;  
  2. using Microsoft.AspNet.Identity;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8.   
  9. namespace JqueryFormValidator.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         #region Register  
  14.   
  15.         //  
  16.         // GET: /Home/Register  
  17.         [AllowAnonymous]  
  18.         public ActionResult Register()  
  19.         {  
  20.             return View();  
  21.         }  
  22.   
  23.         //  
  24.         // POST: /Home/Register  
  25.         [HttpPost]  
  26.         [AllowAnonymous]  
  27.         [ValidateAntiForgeryToken]  
  28.         public ActionResult Register(RegisterViewModel model)  
  29.         {  
  30.             if (ModelState.IsValid)  
  31.             {  
  32.                 // Info.  
  33.                 Console.WriteLine(model.Email);  
  34.             }  
  35.   
  36.             // If we got this far, something failed, redisplay form  
  37.             return View(model);  
  38.         }  
  39.  
  40.         #endregion  
  41.     }  

In the above code. I have simply created "Register" method for both, HTTP Get and HTTP Post methods. Both methods are doing nothing but just validating my form input's basic constraints defined in View Model.

Now, create a new View Model class in "Models" folder and name it "HomeViewModels.cs". Replace the following piece of code in the "HomeViewModels.cs" file.

  1. using System.Collections.Generic;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace JqueryFormValidator.Models  
  5. {  
  6.     public class RegisterViewModel  
  7.     {  
  8.         [Required]  
  9.         [EmailAddress]  
  10.         [Display(Name = "Email")]  
  11.         public string Email { getset; }  
  12.   
  13.         [Required]  
  14.         [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]  
  15.         [DataType(DataType.Password)]  
  16.         [Display(Name = "Password")]  
  17.         public string Password { getset; }  
  18.   
  19.         [DataType(DataType.Password)]  
  20.         [Display(Name = "Confirm password")]  
  21.         [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]  
  22.         public string ConfirmPassword { getset; }  
  23.     }  

In the above code, I have created my View Model for my "Register" UI i.e. "RegisterViewModel" and created three properties in it along with basic validations on those properties. For Email property, I have defined required attribute constraint and email constraint. This will help MVC 5 platform to identify any invalid basic input from end-user.

Now, open "_Layout.cshtml" file from "Shared" folder and replace the code with following.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10.     <!-- Font Awesome -->  
  11.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
  12.   
  13. </head>  
  14. <body>  
  15.     <div class="navbar navbar-inverse navbar-fixed-top">  
  16.         <div class="container">  
  17.             <div class="navbar-header">  
  18.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  19.                     <span class="icon-bar"></span>  
  20.                     <span class="icon-bar"></span>  
  21.                     <span class="icon-bar"></span>  
  22.                 </button>  
  23.             </div>  
  24.         </div>  
  25.     </div>  
  26.     <div class="container body-content">  
  27.         @RenderBody()  
  28.         <hr />  
  29.         <footer>  
  30.             <center>  
  31.                 <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
  32.             </center>  
  33.         </footer>  
  34.     </div>  
  35.   
  36.     @Scripts.Render("~/bundles/jquery")  
  37.     @Scripts.Render("~/bundles/bootstrap")  
  38.   
  39.     @RenderSection("scripts", required: false)  
  40. </body>  
  41. </html> 
In the above code, I have simply created my basic default layout for all pages.

Let's create our "Register.cshtml" View in "Views/Home" folder and place the following code in it

  1. @model JqueryFormValidator.Models.RegisterViewModel  
  2. @{  
  3.     ViewBag.Title = "Register";  
  4. }  
  5.   
  6. <h2>@ViewBag.Title.</h2>  
  7.   
  8. @using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @id = "registerFormId", @class = "form-horizontal"role = "form" }))  
  9. {  
  10.     @Html.AntiForgeryToken()  
  11.     HtmlHelper.UnobtrusiveJavaScriptEnabled = false;  
  12.   
  13.     <h4>Create a new account.</h4>  
  14.     <hr />  
  15.   
  16.     <div class="form-group">  
  17.         @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })  
  18.         <div class="col-md-10">  
  19.             @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })  
  20.             @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger  " })  
  21.         </div>  
  22.   
  23.     </div>  
  24.     <div class="form-group">  
  25.         @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })  
  26.         <div class="col-md-10">  
  27.             @Html.PasswordFor(m => m.Password, new { @class = "form-control" })  
  28.             @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger " })  
  29.         </div>  
  30.   
  31.     </div>  
  32.     <div class="form-group">  
  33.         @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })  
  34.         <div class="col-md-10">  
  35.             @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })  
  36.             @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "text-danger " })  
  37.         </div>  
  38.     </div>  
  39.     <div class="form-group">  
  40.         <div class="col-md-offset-2 col-md-10">  
  41.             <input type="submit" class="btn btn-default" value="Register" />  
  42.         </div>  
  43.     </div>  
  44. }  
  45.   
  46. @section Scripts {  
  47.     @Scripts.Render("~/bundles/jqueryval")  
  48.     @Scripts.Render("~/bundles/custom-validator")  
  49. }   
In the above code, I have attached my View Model "RegisterViewModel" with my "Register" UI. In the above code, notice the following line of code.
  1. HtmlHelper.UnobtrusiveJavaScriptEnabled = false

Change the above property value to true and execute the project followed by a click on "Register" button, without providing any input. You will see the following error messages.

ASP.NET

ASP.NET 

The above images show default client-side validation response of ASP.NET MVC5. Let's change it to that of jQquery form validation instead.

Change "HtmlHelper.UnobtrusiveJavaScriptEnabled" value back to false and create new file in "Scripts" folder  naming it "script-custom-validator.js". Place the following code in it.

  1. $(document).ready(function ()   
  2. {  
  3.     $('#registerFormId').validate({  
  4.         errorClass: 'help-block animation-slideDown'// You can change the animation class for a different entrance animation - check animations page  
  5.         errorElement: 'div',  
  6.         errorPlacement: function (error, e) {  
  7.             e.parents('.form-group > div').append(error);  
  8.         },  
  9.         highlight: function (e) {  
  10.     
  11.             $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');  
  12.             $(e).closest('.help-block').remove();  
  13.         },  
  14.         success: function (e) {  
  15.             e.closest('.form-group').removeClass('has-success has-error');  
  16.             e.closest('.help-block').remove();  
  17.         },  
  18.         rules: {  
  19.             'Email': {  
  20.                 required: true,  
  21.                 email: true  
  22.             },  
  23.   
  24.             'Password': {  
  25.                 required: true,  
  26.                 minlength: 6  
  27.             },  
  28.   
  29.             'ConfirmPassword': {  
  30.                 required: true,  
  31.                 equalTo: '#Password'  
  32.             }  
  33.         },  
  34.         messages: {  
  35.             'Email''Please enter valid email address',  
  36.   
  37.             'Password': {  
  38.                 required: 'Please provide a password',  
  39.                 minlength: 'Your password must be at least 6 characters long'  
  40.             },  
  41.   
  42.             'ConfirmPassword': {  
  43.                 required: 'Please provide a password',  
  44.                 minlength: 'Your password must be at least 6 characters long',  
  45.                 equalTo: 'Please enter the same password as above'  
  46.             }  
  47.         }  
  48.     });  
  49. });   
In the above code, I have defined validation configuration for jQuery form validation. Let's dissect the code chunk by chunk i.e.
  1. $('#registerFormId').validate({  
  2.     errorClass: 'help-block animation-slideDown'// You can change the animation class for a different entrance animation - check animations page  
  3.     errorElement: 'div',  
  4.     errorPlacement: function (error, e) {  
  5.         e.parents('.form-group > div').append(error);  
  6.     },  
  7.     highlight: function (e) {  
  8.   
  9.         $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');  
  10.         $(e).closest('.help-block').remove();  
  11.     },  
  12.     success: function (e) {  
  13.         e.closest('.form-group').removeClass('has-success has-error');  
  14.         e.closest('.help-block').remove();  
  15.     },  
The above piece of code attaches my account register form with jQuery form validator by using form ID. Then, I have defined settings about where to place the error message and its related styling. I have also defined methods for validator that describe what happens when error message is highlighted and form validation is successful.
  1. rules: {  
  2.     'Email': {  
  3.         required: true,  
  4.         email: true  
  5.     },  
  6.   
  7.     'Password': {  
  8.         required: true,  
  9.         minlength: 6  
  10.     },  
  11.   
  12.     'ConfirmPassword': {  
  13.         required: true,  
  14.         equalTo: '#Password'  
  15.     }  
  16. },  
  17. messages: {  
  18.     'Email''Please enter valid email address',  
  19.   
  20.     'Password': {  
  21.         required: 'Please provide a password',  
  22.         minlength: 'Your password must be at least 6 characters long'  
  23.     },  
  24.   
  25.     'ConfirmPassword': {  
  26.         required: 'Please provide a password',  
  27.         minlength: 'Your password must be at least 6 characters long',  
  28.         equalTo: 'Please enter the same password as above'  
  29.     }  
  30. }  
The above piece of code will define our form validation rules and error messages for each input on form. Notice that in the above code that in the rules & messages section, the keyword "Email" is actually the "name" property of input tag that our Razor View Engine automatically generates based on our attached View Model.

Finally, execute the project and click the "Register" button without providing the input data, and you will see the jQuery form validation errors in action, as shown below.

ASP.NET

ASP.NET

Before I end this tutorial, let's talk about the following properties in "web.config" file.

ASP.NET 

  1. <add key="ClientValidationEnabled" value="true" />  
  2.     <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

The above properties are set True by default which means MVC 5 platform ensures that client side validation on form validation is on. For jQuery form validation to work, we set "HtmlHelper.UnobtrusiveJavaScriptEnabled = false;" property false in the register form instead of "web.config" file; this means if we set the value false for above property in "web.config" file, then we will disable client side validation across application.Thus, the preferred practice is to disable the property into the form in which you want to use jQuery form validation.

Conclusion

In this article, you have learned about jQuery form validator, how to use it with ASP.NET MVC 5, how to configure it, how to stop MVC 5 platform client side validation, and how to implement jQuery form validator to your form.

Up Next
    Ebook Download
    View all
    Learn
    View all