ASP.NET MVC5: JQuery Form Validator

1

Form component is important piece of portion on any website that require data input from end-user. It could be account creation form, it could be feedback form or it could be any kind of information registration form etc. Since, the data require on forms are input by end-users, therefore, its responsibility of a web engineer to ensure that what kind of information end-user is allowed to register. So, here come, web form validation into play.

Now, web form validation is of two types i.e.

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

1) Client Side Form Validation -> This type of form validation is done at browser level meaning handling simple constraint validations e.g. checking empty input fields, identifying valid email address, verification of password constraints etc. Client side form validation also help in providing better user interactivity with the website, while deep verification or validation of input data is being done at server side.

2) Server Side Form Validation -> Server side form validation as the name suggest, is done on server side of the web, which involve 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 base client side validator with ASP.NET MVC5 platform. Although, mvc5 platform already facilitate client side validation as a built-in component. However, 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 tutorial:

  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 tutorial or you can follow the step by step discussion below. The sample code is being developed in Microsoft Visual Studio 2015 Enterprise.

Download Link

Now, let’s begin.

1) Create a new MVC web project and name it “JqueryFormValidator“.

2) Make sure that you have installed following two Java Scripts into your “Scripts” folder i.e.

  1. jquery.validate.js
  2. jquery.validate.unobtrusive.js

3) Now, open “RouteConfig.cs” file and replace following code in it i.e.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace JqueryFormValidator
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Register", id = UrlParameter.Optional }
            );
        }
    }
}

 

In the above code, I have simply change my default launch action from “Index” to “Register“.

4) Now, open “BundleConfig.cs” file and replace it with following code i.e.

 

using System.Web;
using System.Web.Optimization;

namespace JqueryFormValidator
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate.js",
                        "~/Scripts/jquery.validate.unobtrusive.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            // JQuery validator. 
            bundles.Add(new ScriptBundle("~/bundles/custom-validator").Include(
                                  "~/Scripts/script-custom-validator.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }
}

 

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 i.e.

 

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate.js",
                        "~/Scripts/jquery.validate.unobtrusive.js"));


           bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

 

5) Create a new controller class in “Controllers” folder and name it “HomeController.cs“. Replace following code in “HomeController.cs” file i.e.

 

using JqueryFormValidator.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace JqueryFormValidator.Controllers
{
    public class HomeController : Controller
    {
        #region Register

        //
        // GET: /Home/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Home/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Info.
                Console.WriteLine(model.Email);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        #endregion
    }
}

 

In the above code. I have simply created “Register” method both for HTTP Get and HTTP Post method. Both methods are doing nothing just validating my form inputs basic constraints defined in view model.

6) Now, create a new view model class in “Models” folder and name it “HomeViewModels.cs“. Replace following piece of code in the “HomeViewModels.cs” file i.e.

 

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace JqueryFormValidator.Models
{
    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}

 

In the above code I have created my view model for my “Register” UI i.e. “RegisterViewModel” and create three properties in it along with basic validations on those properties e.g. for Email property I have defined required attribute constraint and email constraint. This will help mvc5 platform to identify any invalid basic input from end-user.

7) Now, open “_Layout.cshtml” file from “Shared” folder and replace following code in it i.e.

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <center>
                <p><strong>Copyright &copy; @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
            </center>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

    @RenderSection("scripts", required: false)
</body>
</html>

 

In the above code, I have simply created my basic default layout for all pages.

8) Lets create our “Register.cshtml” view in “Views/Home” folder and place following code in it i.e.

 

@model JqueryFormValidator.Models.RegisterViewModel
@{
    ViewBag.Title = "Register";
}

<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @id = "registerFormId", @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    HtmlHelper.UnobtrusiveJavaScriptEnabled = false;

    <h4>Create a new account.</h4>
    <hr />

    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger  " })
        </div>

    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger " })
        </div>

    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "text-danger " })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/custom-validator")
}

 

In the above code, I have attach my view model “RegisterViewModel” with my “Register” UI. In the above code, notice following line of code i.e.

 

HtmlHelper.UnobtrusiveJavaScriptEnabled = false;

 

Change above property value to true and execute the project and click “Register” button, without providing any input. You will see following error messages i.e.

 

02

 

The above images shows default client side validation response of ASP.NET MVC5. Let change that to that of Jquery form validation instead.

9) Change “HtmlHelper.UnobtrusiveJavaScriptEnabled” value back to true and create new file in “Scripts” folder and name it “script-custom-validator.js“. Place following code in it i.e.

 

$(document).ready(function () 
{
    $('#registerFormId').validate({
        errorClass: 'help-block animation-slideDown', // You can change the animation class for a different entrance animation - check animations page
        errorElement: 'div',
        errorPlacement: function (error, e) {
            e.parents('.form-group > div').append(error);
        },
        highlight: function (e) {
  
            $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
            $(e).closest('.help-block').remove();
        },
        success: function (e) {
            e.closest('.form-group').removeClass('has-success has-error');
            e.closest('.help-block').remove();
        },
        rules: {
            'Email': {
                required: true,
                email: true
            },

            'Password': {
                required: true,
                minlength: 6
            },

            'ConfirmPassword': {
                required: true,
                equalTo: '#Password'
            }
        },
        messages: {
            'Email': 'Please enter valid email address',

            'Password': {
                required: 'Please provide a password',
                minlength: 'Your password must be at least 6 characters long'
            },

            'ConfirmPassword': {
                required: 'Please provide a password',
                minlength: 'Your password must be at least 6 characters long',
                equalTo: 'Please enter the same password as above'
            }
        }
    });
});

 

In the above code, I have defined validation configuration for Jquery form validation lets dissect the code chunk by chunk i.e.

 

    $('#registerFormId').validate({
        errorClass: 'help-block animation-slideDown', // You can change the animation class for a different entrance animation - check animations page
        errorElement: 'div',
        errorPlacement: function (error, e) {
            e.parents('.form-group > div').append(error);
        },
        highlight: function (e) {
  
            $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
            $(e).closest('.help-block').remove();
        },
        success: function (e) {
            e.closest('.form-group').removeClass('has-success has-error');
            e.closest('.help-block').remove();
        },

 

The above piece of code attach 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 what happens when error message is highlighted and form validation is successful.

 

        rules: {
            'Email': {
                required: true,
                email: true
            },

            'Password': {
                required: true,
                minlength: 6
            },

            'ConfirmPassword': {
                required: true,
                equalTo: '#Password'
            }
        },
        messages: {
            'Email': 'Please enter valid email address',

            'Password': {
                required: 'Please provide a password',
                minlength: 'Your password must be at least 6 characters long'
            },

            'ConfirmPassword': {
                required: 'Please provide a password',
                minlength: 'Your password must be at least 6 characters long',
                equalTo: 'Please enter the same password as above'
            }
        }

 

The above piece of code will define our form validation rules and error messages for each input on form. Notice in the above code that in rules & messages section the keyword “Email” actually the “name” property of input tag that our razor view engine automatically generate base on our attach view model.

10) 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 i.e.

 

0

1

Before I end this tutorial lets talk about following properties in “web.config” file i.e.

4

 

    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

 

The above properties are set true by default which means mvc5 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 false in “web.config” file then we will disable client side validation across application, instead prefer practice is to disable the property into the form in which you want to use Jquery form validation.

Conclusion

In this article, you will learn about Jquery form validator, how to use Jquery form validator with ASP.NET MVC5, how to configure Jquery form validator, how to stop mvc5 platform client side validation and how to attach Jquery form validator to your form.

Leave a Reply