jQuery Validation of Email, Number. Dropdown, Checkbox & Radio Button

jQuery Validation of Email, Number. Dropdown, Checkbox & Radio Button

jQuery is the most popular JavaScript Library which is not only light weight, superfast, all browser compatible but also excellent in creating animations, event handling, AJAX calls and html/CSS/DOM manipulation. It is necessary that all web developers should have a good knowledge of jQuery so that he or she can use it to provide a good client side features to their web applications.

jQuery is used mainly for 3 things which are:
  • 1. Form Validation in the client side or browser side. This makes application faster and easy to use. Client side form validation also helps in reducing the unnecessary server load.
  • 2. DOM Manipulation is very easy with jQuery. You can capture html elements in the DOM(Document Object Model) by their name, css, parent and children and can edit their properties with just 2 to 3 lines of codes. The tutorial on jQuery expand collapse shows how excellent features can be developed with jQuery.
  • 3. Event handling is made easy in jQuery, through which you can capture the click, focus, hover and other events of buttons, images, div, etc. It is also very easy to call server side codes with jQuery AJAX.

In this tutorial we will explain you how to do jQuery Form Validation. Our form is a job application one where users can fill and submit it online. We want that users should submit their information in proper manner like proper age, proper email, etc. Therefore we have used jQuery form validation.

Form Controls Which We Will Validate

Our form has six fields and we have used different controls for them –

  • 1. Name – input of type ‘text’
  • 2. Age – input of type ‘text’
  • 3. Email – input of type ‘text’
  • 4. Sex – ‘Select’ control
  • 5. Are You Married? – input of type ‘checkbox’
  • 6. You Have US Work Permit? – input of type ‘radio’

Besides these there is a div which will show validation error messages and a input of type ‘submit’ in the end to submit the information.

Not only validations, you can apply jQuery to enhance the look of your website in many ways. Do check the article on creating Fantastic Ways to Make Website Navigation Bar Look Staggering.

Follow the below Steps To add jQuery Validation

1. Add Controls and CSS In The Page

<div id="content">
    <h1>Apply For a Job</h1>
    <div id="errorDiv"></div>
    <table>
        <tr>
            <td>Name:-</td>
            <td><input type="text" id="nameInput"/></td>
        </tr>
        <tr>
            <td>Age:-</td>
            <td>input type="text" id="ageInput"/></td>
        </tr>
        <tr>
            <td>Email:-</td>
            <td><input type="text" id="emailInput" /></td>
        </tr>
        <tr>
            <td>Sex:-</td>
            <td>
                <select id="sexSelect">
                    <option value="Select">Select Your Sex</option>
                    <option value="M">Male</option>
                    <option value="F">Female</option>
                </select>
            </td>
        </tr>
        <tr>
            <td>Are You Married?:-</td>
            <td>(Yes or Checked/No for UnChecked)<input type="checkbox" title="Yes" id="marriedCheckBox"/>                                                                                                 
            </td> 
        </tr>
        <tr>
            <td>You Have US Work Permit?:-</td>
            <td>Yes<input type="radio" id="workPermitYesRadio" name="workPermitYesRadio" value="Yes"/><br />
                No<input type="radio" id="workPermitNoRadio" name="workPermitYesRadio" value="No" />
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" id="submitButton" value="Apply"/></td>
        </tr>
    </table>
</div>
#content {
    margin: 0 auto;
    width: 960px;
    background-color: #cccccc;
}

    #content h1 {
        text-align: center;
        text-decoration: underline;
    }

table {
    width: 100%;
}

    table tr td {
        width: 40%;
        text-align: center;
    }

#errorDiv {
    background-color: red;
    color: #FFFFFF;
    padding-left:25px;
}
jQuery Form Validation

jQuery Form Validation

2. Add the link to jQuery file

<script type="text/javascript" src="JS/jquery-2.1.1.js"></script>

Put this link just before the body end tag ‘</body>’. Here we have placed the jQuery file in our ‘JS’ folder. You can download jQuery file from http://jquery.com/download/. We advise you to use the most stable version which is 2.1.1 version, click the link ‘Download the uncompressed, development jQuery 2.1.1’ on the page.

3. Adding jQuery Event Handling

Add the below lines just after where you have put jQuery link

<script type="text/javascript">
    $(document).ready(function () {
         $("#submitButton").click(function (e) {
            ValidateAll();
            return false;
        });
    });
</script>

4. Add jQuery validation Functions

Just after jQuery event handling code add the below code which contains our validation function.

<script type="text/javascript" lang="javascript">
    function EmailValidate() {
        var numericExpression = /^w.+@[a-zA-Z_-]+?.[a-zA-Z]{2,3}$/;
        var elem = $("#emailInput").val();
        if (elem.match(numericExpression))
            return true;
        else
            return false;
    }

    function ValidateAll() {
        var errorCounter = 0;
        var errorMessage = "";
        //Name
        if ($("#nameInput").val() == '') {
            errorMessage += " Enter your Name<br/>";
            errorCounter++;
        }
        //End
           
        //Age
        if ($("#ageInput").val() == '') {
            errorMessage += " Enter your age<br/>";
            errorCounter++;
        }
        else if (!$.isNumeric($("#ageInput").val()))
        {
            errorMessage += " Invalid age-should be numeric<br/>";
            errorCounter++;
        }
        //End
            
        //Email
        if ($("#emailInput").val() == '') {
            errorMessage += " Enter your email address<br/>";
            errorCounter++;
        }
        else if (!(EmailValidate())) {
            errorMessage += " Invalid email address<br/>";
            errorCounter++;
        }
        //End

        //Sex
        if ($("#sexSelect").val() == 'Select') {
            errorMessage += " Please select your sex<br/>";
            errorCounter++;
        }
        //End
           
        //Married
        if (!($('#marriedCheckBox').prop('checked')))
        {
            errorMessage += " You should be married if you want to apply for this job.<br/>";
            errorCounter++;
        }
        //End

        //Work Permit
        if ((!($('#workPermitYesRadio').prop('checked'))) && (!($('#workPermitNoRadio').prop('checked')))) {
            errorMessage += " Tell us your work permit status.<br/>";
            errorCounter++;
        }
        else if (!($('#workPermitYesRadio').prop('checked'))) {
            errorMessage += " You should have US work permit if you want to apply for this job.<br/>";
            errorCounter++;
        }
        //End

        $("#errorDiv").html(errorMessage);
        if (errorCounter == 0) {
            alert('Thank you, your job application has been submitted successfully. We will contact you soon.')
            return true;
        }
        else
        {
            return false;
        }
    }
</script>

Our page is now ready for validation. Here we have attached the ‘click’ event of submit button which calls the ‘ValidateAll()’ custom function. It checks if all the values of the controls are proper or not. If user tries to put improper values he is shown an error message. If he puts all his information properly the form is submitted. This time the event hander code returns ‘true’ and the form is posted back. We can capture it on our server side code by using ‘asp.net’ or ‘php’ page and can store the submitted information in the database.

jQuery Validate Email

To Validate email, we match the email with the regular expression ‘/^w.+@[a-zA-Z_-]+?.[a-zA-Z]{2,3}$/’. If the match return true then the email format is correct. Below is the function which does this work-

function EmailValidate() {
    var numericExpression = /^w.+@[a-zA-Z_-]+?.[a-zA-Z]{2,3}$/;
    var elem = $("#emailInput").val();
    if (elem.match(numericExpression))
        return true;
    else
        return false;
}

To check email value in the textbox using the above function, we have used –

if ($("#emailInput").val() == '') {
    errorMessage += " Enter your email address<br/>";
    errorCounter++;
}
else if (!(EmailValidate())) {
    errorMessage += " Invalid email address<br/>";
    errorCounter++;
}

jQuery Validate Number

To check if the value in a textbox is a number only. We use ‘isNumeric’ jQuery function. So our code to validate number in jQuery is –

if ($("#ageInput").val() == '') {
    errorMessage += " Enter your age<br/>";
    errorCounter++;
}
else if (!$.isNumeric($("#ageInput").val()))
{
    errorMessage += " Invalid age-should be numeric<br/>";
    errorCounter++;
}

jQuery Validate Dropdown

If the dropdown value is ‘Select’ then our validation fails. So our dropdown validation function is –

if ($("#sexSelect").val() == 'Select') {
    errorMessage += " Please select your sex<br/>";
    errorCounter++;
}

jQuery Validate Checkbox

To Validate Checkbox we have used ‘prop’ function. Our code to validate checkbox is –

if (!($('#marriedCheckBox').prop('checked')))
{
    errorMessage += " You should be married if you want to apply for this job.<br/>";
    errorCounter++;
}

You may like to see our tutorial jQuery Uncheck Checkbox to learn more about using jQuery in Checkbox.

jQuery Validate Radio Button

Similary like checkbox, we have used prop to validate radio button. Our code is –

if ((!($('#workPermitYesRadio').prop('checked'))) && (!($('#workPermitNoRadio').prop('checked')))) {
    errorMessage += " Tell us your work permit status.<br/>";
    errorCounter++;
}
else if (!($('#workPermitYesRadio').prop('checked'))) {
    errorMessage += " You should have US work permit if you want to apply for this job.<br/>";
    errorCounter++;
}

DEMO DOWNLOAD

Other jQuery Function Used:
  • $(“#nameInput”).val() – get the value of the control having id ‘nameInput’.
  • $(‘#workPermitYesRadio’).prop(‘checked’))) – finds if the control (id ‘workPermitYesRadio’) is checked or not.
  • $(“#errorDiv”).html(errorMessage) – shows the error message inside the div with id ‘errorDiv’.

Conclusion
This jQuery Validation tutorial explains how to validate different controls on the client side. You can enhance this feature based on your requirements. If you have any query please enter it in the comment section below, we hope to answer your queries as soon as possible.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.