Jquery Tooltip validation Using Twitter Bootstrap in MVC 5 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Wednesday, 20 April 2016

Jquery Tooltip validation Using Twitter Bootstrap in MVC 5

05:22:00 Posted by raviteja swayampu , 1 comment
Hello every one welcome again.I hope my last post "file upload using Ajax" helped you a lot.There are more programming examples and sample code are avilable in this site.I am always want to share my knowledge. Because, by sharing knowledge i can able to more.
In this article i am gonna teach you "Jquery tooltip valiadation using twitter bootstrap".Generally we use "Jquery unobtrusive validation plugin" in ASP.NET MVC applications.
Topics we are going to discuss in this article:
1.Disadvantages of Jquery unebtrusive validation in MVC.
2.Jquery tooltip validation

There are some disadvantage of using this plugin.When using Jquery unobtrusive validation plugin it creates a span tag to dispplay error messages.If you have, for example, a horizontal form on top of other controls then this behavior might not be working for you since they will break the page layout. It was the case for me and as such I decided to change the default behavior of the JQuery unobtrusive validation library and instead of using a span to show the error message I decided to use a tooltip.I am going to show you how i acheived this using a tooltip with help of bootstrap.

Before going to tooltip validation first look at the traditional jquery unobtrusive example..
The following is a example application of unobtrusive validation.

jquery-tooltip-validation-using-bootstrap-in-mvc5

when i click on Register button then error messages look like this

jquery-tooltip-validation-using-bootstrap-in-mvc5
If i increases the length of error message the layout will be breaked like this.In the same way when i place the same lengthy error message below the Textbox controls insted of beside the controls as shown in screenshot same layout change problem occurs.So,This is a bad idea of using default behaviour of Jquery Unebtrusive validation plugin.I replaced the error type with tooltip.it won't chage the layout structure.
Now Jquery tooltip validation article begins from here,

Jquery tooltip validation using Twitter Bootstrap

Step 1: Create a ASP.NET MVC application
1. create a application with MVC template.

jquery-tooltip-validation-using-bootstrap-in-mvc5

2.Add following files to the solution

jquery-tooltip-validation-using-bootstrap-in-mvc5

3.create HomeController.cs:
   a.right click-->Controllers folder-->Add-->Controller-->Name it as HomeController.cs.

jquery-tooltip-validation-using-bootstrap-in-mvc5

4.Add Index Method to controller.
5.Add View to Index Action method
   a.Right click-->Index Method-->Add View-->Click Ok.

jquery-tooltip-validation-using-bootstrap-in-mvc5

   b.Index view created.

6.Now replace the code Index.cshtml code with below code.
<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap tooltip Example</title>

    <!-----------------resource files------------->
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery-validate.bootstrap-tooltip.min.js"></script>
    <script src="~/Scripts/myscript.js"></script>

</head>
<body>
<div id="main">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { name = "RegistrationForm", id = "RegistrationForm" }))
    {
        <fieldset style="padding-left: 100px; box-shadow: 2px 2px 2px 2px #000;margin-top:30px;height:500px;">
            <legend style="font-size:larger;font-weight:bold;">Registration page</legend>
            <div id="left-part" align="left" style="float:left;margin-left:20px;">
                @Html.Label("FirstName", new { required = "required" })<br />
                @Html.TextBox("FirstName")<br /><br />
                @Html.Label("LastName")<br />
                @Html.TextBox("LastName")<br /><br />
                @Html.Label("UserName")<br />
                @Html.TextBox("UserName")<br /><br />
                @Html.Label("Gender")<br />
                @Html.RadioButton("Gender", "Male", false, new { id = "rbnMale", name = "rbnMale" })Male
                @Html.RadioButton("Gender", "Female", false, new { id = "rbnFemale", name = "rbnFemale" })Female
                <br /><br />
                @Html.Label("Email Id:")  <br />
                @Html.TextBox("Email", null, new { type = "email" })<br /><br />
            </div>
            <div id="right-side" style="margin-left:400px;">
                @Html.Label("Password")<br />
                @Html.Password("Password")<br /><br />
                @Html.Label("ConfirmPassword")<br />
                @Html.Password("ConfirmPassword")<br /><br />
                @Html.Label("MobileNo")<br />
                @Html.TextBox("MobileNo", null, new { type = "number" })<br /><br />
                @Html.Label("State")<br />
                @Html.TextBox("State")<br /><br />
                @Html.Label("Country")<br />
                @Html.DropDownList("CountryDropdownlst", new List<SelectListItem>()
                         {
                            new SelectListItem(){Text="India",Value="0"},
                            new SelectListItem(){Text="China",Value="1"},
                            new SelectListItem(){Text="USA",Value="2"},
                            new SelectListItem(){Text="Russia",Value="3"}
                         }, "--select--", new { id = "CountryDropdownlst" })
                <br /><br />
                <input type="submit" value="Register" id="btnSubmit" name="btnSubmit" class="btn btn-primary"/>
            </div>
        </fieldset>
    }
    <br />
</div>
</body>
</html>

Step 2: Add script for validation
1.Add myscript.js to the script folder..

myscript.js:

//if no errors form will be submited
$.validator.setDefaults({
    submitHandler: function () {
        alert("form submited!");
    }
});
debugger;
$(document).ready(function () {
    $("#RegistrationForm").validate({
        rules: {
            FirstName: {
                required: true,
                minlength: 4,
                maxlength: 15
            },
            LastName: {
                required: true,
                minlength: 4,
                maxlength: 15
            },
            UserName: {
                required: true,
                minlength: 5
            },
            Gender: { required: true },
            Email: {
                required: true,
                email: true
            },
            Password: {
                required: true,
                minlength: 5,
                maxlength: 20
            },
            ConfirmPassword:{
                required: true,
                equalTo:"#Password"
            },
            MobileNo: {
                required: true,
                number: true,
                minlength: 10,
                maxlength:12
            },
            State: { required: true ,minlength:5},
            CountryDropdownlst: {
                required:true
            }
        },
        messages: {
            Gender: "Pls Select the Gender!",
            FirstName: {
                required: "Firstname required Firstname required Firstname required Firstname required ",
                minlength: "pls enter min 4 chars",
                maxlength:"only 15 chars are allowed"
            },
            LastName: {
                required: "Lastname required",
                minlength: "pls enter min 4 chars",
                maxlength: "only 15 chars are allowed"
            },
            UserName: {
                required: "Username is mandatory",
                minlength:"pls enter min 5 chars"
            },
            Password: {
                required: "Password is mandatory",
                minlength:"pls enter min 5 chars"
            },
            ConfirmPassword: {
                required: "Pls confirm password",
                equalTo:"password does not match"
            },
            MobileNo: {
                required: "pls enter mobile no",
                minlength: "pls enter valid mobile no"
            },
            State:"Pls enter valid state",
            CountryDropdownlst:"pls select your country"

        },
        //tooltip options to change position of tooltip..
        tooltip_options: {
            FirstName: { trigger: 'focus' },
            Gender: { placement: 'top', html: true }    //placement:'bottom'for bottom
        },
        //submitHandler: function (form) {
        //    $("#validity_label").html('
No errors. Like a boss.
'); //}, invalidHandler: function (form, validator) { $("#validity_label").html('
There be ' + validator.numberOfInvalids() + ' error' + (validator.numberOfInvalids() > 1 ? 's' : '') + ' here. OH NOES!!!!!
'); } }); });

Step 3:
1.Add styles for error display.

 .tooltip{
            margin-left:100px;           
        }
        .tooltip-inner {
            background: #ff3333; /*tooltip text background color*/
            border-radius: 0px;
            font-weight: bolder;
            box-shadow: 1px 1px 1px 1px black;
        }
        .tooltip.top .tooltip-arrow {
            border-top-color: red;
            margin-left: -55px;           
        }
        input[type="text"],input[type="password"],input[type="number"],input[type="email"], #CountryDropdownlst {
            box-shadow: 1px 1px 1px 1px grey;
            width: 200px;
        }
        #CountryDropdownlst{
            height:27px;
        }
        /*.tooltip-inner tooltip-arrow {
            margin-left: 200px;
        }*/

Now run application you will get window like this..


jquery-tooltip-validation-using-bootstrap-in-mvc5
Without entering anything into fields just click on Register button button and see what happens.

jquery-tooltip-validation-using-bootstrap-in-mvc5
In above screen shot if i increases the length of error message layout does not change.
Downlaod source code Download.

Related Articles:

Conclusion:
I hope this article is understandable for every reader.It also helpful in real time projects.If you recommend any suggestion for improving this article i am always welcome.


1 comment: