Thursday, 7 April 2016

Jquery Validation plugin in MVC 4

Leave a Comment
What is jquery validation plugin. I think you got this question. It is one of the plugin used along with Jquery. It is a open source plugin we can shape this according to our requirement.
This plugin simplifies client side validation and also offers plenty of customization options. It makes a good choice is you are building some thing from scratch.but also when you’re trying to integrate something into an existing application with lots of existing markup. The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 other languages.

Note:
official site of this jquery validation plugin is jqueryvalidation.org.you can get code from here and official documentation for this also avilable on this site.

In this article i will explain a simple example of using jquery validation plugin using ASP.NET MVC.
and how  it used in ASP.NET MVC.

Step 1: Create a ASP.NET MVC application using Empty template.
1.open visual studio 2015.
2.select Visual C# -->web-->ASP.NET Web application-->New project window-->select Empty -->Check MVC on bottom-->Add.
3.Project created.

Step 2: Create a Controller
1.Right click Controllers folder-->Add-->Controller-->Select MVC5 Empty Controlller-->name it as "HomeController".
2.generated controller code is like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace jqueryvalidationplugin.Controllers
{
    //Generated controller code is.......
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

Step 3: Add libreary files/resource files to view.
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/mytechdev_script.js"></script>

Note: After adding this libreary files to index view goto _Layout.cshtml page and check is there any bootstrap,jquery reference files are added.If they was added comment those resource files.like this.
And you can download the code from official site mentioned in the above link.

Step 4: Add view to Index action Method 1.Right click on Index action method-->Add View-->Select Empty template-->Click Add. replace code with following code for displaying Form: Index.cshtml:
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">Simple Form</h3>
    </div>
    <div class="panel-body">
        <form id="signupForm" method="post" class="form-horizontal" action="">
            <div class="form-group">
                <label class="col-sm-4 control-label" for="firstname">First name</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="firstname" name="firstname" placeholder="First name" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="lastname">Last name</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="lastname" name="lastname" placeholder="Last name" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="username">Username</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="username" name="username" placeholder="Username" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="email">Email</label>
                <div class="col-sm-5">
                    <input type="text" class="form-control" id="email" name="email" placeholder="Email" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="password">Password</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" id="password" name="password" placeholder="Password" />
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-4 control-label" for="confirm_password">Confirm password</label>
                <div class="col-sm-5">
                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm password" />
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-5 col-sm-offset-4">
                    <div class="checkbox">
                        <label>
                            <input type="checkbox" id="agree" name="agree" value="agree" />Please agree to our policy
                        </label>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-9 col-sm-offset-4">
                    <button type="submit" class="btn btn-primary" name="signup" value="Sign up">Sign up</button>
                </div>
            </div>
        </form>
    </div>
</div>
Step 5: Add script file for validation 1.Add a mytechdev_script.js file to the project in Scripts folder. Note: I added the explanation for code in the script itself.
//this 'setDefaults' checks entire form and executed after 
//there is no errors
$.validator.setDefaults({
    submitHandler: function () {
        //you will get alert there is no errors in form.
        alert( "form submitted!" );
    }
} );
//These plugin is in json format
//All data we sent is in json format.. like below
//jquery event handler loads after all page loads
$(document).ready(function () {
    //plugin validate function
    $("#signupForm").validate({
        //rules for the validation if form values doen't 
        //satify these rules error is displayed
        rules: {
            firstname: "required",  //fields
            lastname: "required",
            username: {
                required: true,
                minlength: 2
            },
            password: {
                required: true,
                minlength: 5
            },
            confirm_password: {
                required: true,
                minlength: 5,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            },
            agree: "required"
        },
        //if field value doesn't satify above rules following error may arise
        messages: {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            username: {
                required: "Please enter a username",
                minlength: "Your username must consist of at least 2 characters"
            },
            password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
            },
            confirm_password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long",
                equalTo: "Please enter the same password as above"
            },
            email: "Please enter a valid email address",
            agree: "Please accept our policy"
        },
        errorElement: "em",
        //error placement function 
        //we add styles to the error classes here.
        errorPlacement: function (error, element) {
            // Add the `help-block` class to the error element
            error.addClass("help-block");

            if (element.prop("type") === "checkbox") {
                error.insertAfter(element.parent("label"));
            } else {
                error.insertAfter(element);
            }
        },
        //styles for highlighiting successful value
        highlight: function (element, errorClass, validClass) {
            $(element).parents(".col-sm-5").addClass("has-error").removeClass("has-success");
        },
        //styles for highlighiting error value
        unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".col-sm-5").addClass("has-success").removeClass("has-error");
        }
    });
});
Now run the application press F5.. window is look like this...
When i click on signup form without entering any values into the fields then page look like this..

Check the application by submitting different values into the fields. Download source from here Downlaod  Conclusion: I hope you understand this article and it will very helpful to you also. I will met you again in another article.

0 comments:

Post a Comment