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
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 changed my default launch action from "Index" to "Register".

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.

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.

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

In the above code, I have attach my view model "RegisterViewModel" with my "Register" UI. Notice following line of code 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.

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 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.
rules: {
    'Email': {
          required: true,
          email: true 5.
    },
    'Password': {
        required: true,
        minlength: 6 10.
    },
         '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 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.
 
 
 
 
Before I end this tutorial, let's talk about the following properties in "web.config" file.
 
 
 
<add key="ClientValidationEnabled" value="true" />   
<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.


Similar Articles