Header Ads

ASP.NET MVC5: JQuery Form Validator


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 Now! or JQuery 3.2.1 Upgrade

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) As per my provided solution, change default action to "Register" instead of "Index" in  "RouteConfig.cs" file as shown below i.e.


... 

static void RegisterRoutes(RouteCollection routes) { ...  
routes.MapRoute( ... 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) Include jquery.validate.js, jquery.validate.unobtrusive.js and script-suctom-validator.js javascripts path in "BundleConfig.cs" file as shown below i.e.


...

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/jqueryval").Include( "~/Scripts/jquery.validate.js", "~/Scripts/jquery.validate.unobtrusive.js")); ... // JQuery validator. bundles.Add(new ScriptBundle("~/bundles/custom-validator").Include( "~/Scripts/script-custom-validator.js")); } }
...

 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.

5) Create a new controller class in "Controllers" folder and name it "HomeController.cs". Create "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" and add following piece of code as shown below 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.  

8) Create "Register.cshtml" view 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. 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 default error messages set by the MVC platform i.e.



The above images shows default client side validation response of ASP.NET MVC5 if I set the HtmlHelper.UnobtrusiveJavascriptEnabled property true, which is platform default behavior. To change this default behavior and to activate the Jquery form validation instead, you need to change this property value to false at your form level.

9) Now first change "HtmlHelper.UnobtrusiveJavaScriptEnabled" property value back to false and create a new file in "Scripts" folder and name it "script-custom-validator.js". Add the Jquery validator code in it as shown below 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 will happen 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.



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


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

7 comments:

  1. Shop Online in Auckland Newzealand on a single click. We provide you quality items which you will be buy online at lowest price..! Buy online sofa beds nz at lowest price on Treasurebox store.

    ReplyDelete
  2. Abs-cbn serial and gma shows are totally free on pinoy Channel

    ReplyDelete
  3. Here you can see the result of the Nagaland State Lottery Sambad every day on this internet site. You can see the result of the morning of Nagaland at 11:30 am, the result of the day of the state of Nagaland at 6 pm and the result of the national lottery of Nagaland at eight o’clock. Pm The Lottery Sambad itself is known as the result of the Nagaland Country Lottery for the closing results of the Lottery of the Kingdom of Nagaland every day. Upload this website to the bookmark In this web site we update the Nagaland state lottery daily at 11.55 am, Nagaland National Lottery at 4 pm, Nagaland National Lottery every day at 8 pm You can download the results of this Nagaland Country Lottery in PDF format. ۔

    ReplyDelete
  4. hey there, your site is fantastic. I do thank you for work nyc web designer

    ReplyDelete
  5. My spouse and i were very thankful that Edward managed to deal with his basic research from your precious recommendations he was given using your blog. It’s not at all simplistic to just choose to be offering techniques which others could have been trying to sell. And now we do know we now have the blog owner to be grateful to because of that. Most of the explanations you’ve made, the straightforward site navigation, the friendships you assist to create - it’s all astonishing, and it’s really facilitating our son in addition to the family imagine that that issue is pleasurable, and that’s extremely mandatory. Thank you for all the pieces! website design company nyc

    ReplyDelete
    Replies
    1. Glad to be of help and thank you for your kind words and support.

      Delete
  6. Merely wanna input that you have a very nice web site , I love the pattern it actually stands out. brand identity design agency

    ReplyDelete