How to validate a form in realtime using jquery ~ MiTechDev.com

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

Tuesday, 22 August 2017

How to validate a form in realtime using jquery

05:38:00 Posted by raviteja swayampu No comments
Hi every one welcome again with another real time application.In this post we will see about how to perform validations on forms using Jquery.You know there are many ways to perform validations on data entry forms in ASP.NET MVC for example,
1.Using Data Annotations
2.Using Validation plugins
But in real time developers do not consider the option of validation using data annotations.There are some limitations in using Data annotations.It destroys the layout structure if the validation message is long.And developers go for validation plugins for specific purposes only.for example if client wants validations messages to be displayed as tool tips that time they opt one jquery plugin that fits for his functionality.Generally they for jquery normal validations.

Validating form with Jquery:

Requirements:Jquery library(i used v1.10.2),Bootstrap3 for styling form.Add both references in _Layout.cshtml page.
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
In this post we will see how to perform validations on form using jquery.
1.I created a html form that contains most used html controls like textbox,radio button,checkboxes etc.
2.I used Bootstrap Css framework to style it.see the below code.
3.Index.cshtml:
@{
    ViewBag.Title = "Index";
}
<style type="text/css">
    input{max-width:500px;}
</style>
<h3 class="text-info">Realtime Form Validation Using Jquery</h3>

<div class="container">
    <div class="row">
        <form id="frmRegistration">
            <div class="form-group">
                <label class="text-info">Full Name:</label>
                <input type="text" class="form-control" id="txtFullName" onkeypress="return blockSpecialChar(event);" />
                <span style="color:red;" id="spntxtFullName"></span>
            </div>
            <div class="form-group">
                <label class="text-info">UserName:</label>
                <input type="text" class="form-control" id="txtUserName" />
                <span style="color:red;" id="spntxtUserName"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Password:</label>
                <input type="password" class="form-control" id="txtPassword" />
                <span style="color:red;" id="spntxtPassword"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Confirm Password:</label>
                <input type="password" class="form-control" id="txtConfirmPassword" />
                <span style="color:red;" id="spntxtConfirmPassword"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Email:</label>
                <input type="email" class="form-control" id="txtEmail" />
                <span style="color:red;" id="spntxtEmail"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Contact No:</label>
                <input type="text" maxlength="12" class="form-control" id="txtContactNo"  onkeypress="return blockSpecialChar(event);" />
                <span style="color:red;" id="spntxtContactNo"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Gender:</label>
                <input type="radio" value="Male" id="rdnMale" name="gender" />Male
                <input type="radio" value="Female" id="rdnFemale" name="gender" />Female
                <span style="color:red;" id="spnrdlgender"></span>
            </div>
            <div class="form-group">
                <label class="text-info">Country:</label>
                <select id="ddlCountry" class="form-control">
                    <option value="" selected="selected">--select country--</option>
                    <option value="India">India</option>
                    <option value="Jermany">Jermany</option>
                    <option value="Japan">Japan</option>
                    <option value="China">China</option>
                    <option value="United States">United States</option>
                    <option value="Mexico">Mexico</option>
                    <option value="Russia">Russia</option>
                    <option value="United Kingdom">United Kingdom</option>
                    <option value="Canada">Canada</option>
                    <option value="South korea">South korea</option>
                    <option value="Israil">Israil</option>
                    <option value="Austrila">Austrila</option>
                    <option value="France">France</option>
                    <option value="Spain">Spain</option>
                </select>
                <span style="color:red;" id="spnddlCountry"></span>
            </div>
            <div class="form-group">
                <input type="checkbox" id="chkpolicy" />&nbsp;I Agree to policy
                <span style="color:red;" id="spnchkpolicy"></span>
            </div>
            <div class="form-group">
                <input type="button" id="btnSubmit" onclick="return validateform();" class="btn btn-success" value="Submit" />
            </div>
        </form>
    </div>
</div>
4.The form look like below..
5.To perform validation on above form i wrote below jquery script.This script is fired when we click on submit button present at the end of form.
function validateform() {
        var result = true;
        var emailReg = /^([\w-\.][email protected]@([\w-]+\.)+[\w-]{2,4})?$/i;
        var phoneReg= /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
        //Validating a normal textbox
        if ($("#txtFullName").val() == "") {
            $("#spntxtFullName").text("Full Name Required");
            result = false;
        } else {
            $("#spntxtFullName").text("");
        }
        if ($("#txtUserName").val() == "") {
            $("#spntxtUserName").text("UserName Required");
            result = false;
        } else {
            $("#spntxtUserName").text("");
        }
        if ($("#txtPassword").val() == "") {
            $("#spntxtPassword").text("Password Required");
            result = false;
        } else {
            $("#spntxtPassword").text("");
        }
        if ($("#txtPassword").val() != "") {
            if ($("#txtConfirmPassword").val() != $("#txtPassword").val()) {
                $("#spntxtConfirmPassword").text("Password not matched");
                result = false;
            } else {
                $("#spntxtConfirmPassword").text("");
            }
        }
        if ($("#txtEmail").val() == "") {
            $("#spntxtEmail").text("Email Required");
            result = false;
        }
        //validating email with regular expression
        else if (!emailReg.test($.trim($("#txtEmail").val()))) {
            $("#spntxtEmail").text("Valid Email Required");
            result = false;
        }else {
            $("#spntxtEmail").text("");
        }
        if ($("#txtContactNo").val() == "") {
            $("#spntxtContactNo").text("Contact Required");
            result = false;
        }
        //validating phone number with regular expression
        else if (!phoneReg.test($.trim($("#txtContactNo").val()))) {
            $("#spntxtContactNo").text("Valid Contact Required");
            result = false;
        } else {
            $("#spntxtContactNo").text("");
        }
        //validating radio button checked or not
        if (!$("input[name='gender']:checked").val()) {
            $("#spnrdlgender").text("Select Gender");
            result = false;
        } else {
            $("#spnrdlgender").text("");
        }
        //validating checkbox
        if ($("#chkpolicy").prop('checked')==false) {
            $("#spnchkpolicy").text("Select Policy");
            result = false;
        } else {
            $("#spnchkpolicy").text("");
        }
        //validating dropdownlist
        if ($("#ddlCountry").val() == "") {
            $("#spnddlCountry").text("Select country");
            result = false;
        } else {
            $("#spnddlCountry").text("");
        }
        return result;
    }
6.I used regular expressions to check whether contact number and email fields are in correct format.
7.finally below java script function restricts user without entering special characters in FullName and ContactNumber fields.
8.It fires on keypress and blocks special characters.below is code..
//blocks the special characters in textbox.
    function blockSpecialChar(e) {
        var k;
        document.all ? k = e.keyCode : k = e.which;
        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
    }
9.If i click on submit button without giving any data in form fields we will get validations message like below..


10.Download source code for this application from here Download.

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

0 comments:

Post a Comment