Examples Using jQuery Language
 
 

Years ago, developers used a combination of JavaScript and backend coding to detect if a user fully filled out a web form. As you know, the jQuery language is a framework built on JavaScript, but it makes the process of form validation much simpler than older JavaScript techniques. In this article, we'll show you how to validate form input. Just note that you still want to have some backend validation after the user submits the form data, but you can perform a simple review of the data to ensure that required form fields have a value before you submit to the backend web server code.

The Purpose of Frontend Form Validation

Your backend server processes most of the critical tasks for your site. If you have millions of users that visit your site each month, you can take some of the load off of the server if you create client-side validation for basic checks and balances. You shouldn't use JavaScript or jQuery for complex validation, because some users decide to turn off JavaScript in their browsers. This renders form validation on the client unusable, and it's the reason you should always have backend validation as well. However, since most users have JavaScript enabled, this code will work most of the time and it will reduce the traffic sent to your web server just to send back a notice that the user didn't fill out required fields.

Most developers use jQuery to check validation for simple reasons such as if the required field is blank or the format of an input string doesn't match requirements. For instance, you might want to check if a phone number entered is all numbers or an email address has the right format.

In this example, we will have two required form input fields. The first one will be the user's name. The second one will be the user's phone number, and we want to ensure that the input used is all numbers with the proper phone number format.

The HTML Setup

Just like the previous example, we need to first set up the HTML page. Remember that we need to link to the jQuery framework file to use it with our client-side scripting. We also need to set up the form elements that we'll use to send data to the server.

The following code is the HTML file that we'll use for our jQuery validation code.

<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js">></script>

<style>

            .error {

            display: none;

            margin-left: 20px;

            }                      

            .showerror {

            color: red;

            margin-left: 20px;

            }

</style>

</head>

<body>

<div id="inputform">

            <form id="contactinfo" method="post" action="">

            <!-- Name -->

            <div>

                        <label for="name">Name:</label>

                        <input type="text" id="name" name="name"></input>

                        <span style="display: none" id="verifyname">This field is required</span>

            </div>

            <!-- Phone -->

            <div>

                        <label for="phone">Email:</label>

                        <input type="text" id="phone" name="phone"></input>

                        <span style="display: none" id="verifyphone">A valid phone number is required</span>                                               

            </div>

            <div id="submitcontainer">                                               

                        <button type="submit" id="formsubmit">Submit</button>

            </div>

            </form>

</div>

</body>

</html>

We used inline CSS to illustrate the style classes that we'll use to show and hide the warning message. You should take these classes and place them in an external style sheet just to keep your code organized. The warning messages are automatically hidden, because we don't want to show the message unless the user types an improper format or leaves the required field blank.

The HTML page has two form input text boxes. We've left the "action" property blank, because we will override the default behavior and validate the form input before we submit to the backend server.

The jQuery Code

With the input form set up, we can now create our jQuery validation code. We override the submit function, so we want to fire the jQuery validation process when the user clicks the submit button.

As with any jQuery code, before you should always start your event triggers with the "document.ready" function. This ensures that the HTML document is loaded and your jQuery can access all the DOM elements.

$(document).ready(function() {

            //form validation code is here

});

With the DOM verified as ready, we can move on to writing our validation code. We want to validate the form when the user clicks the submit button, so we override the click function on the "formsubmit" button.

$(document).ready(function() {

            $("#formsubmit").click(function(event) {

                        //form validation statements

            });

});

The above code is what we've seen before. We override the formsubmit element's click event. This is where we place all of our validation code.

The first validation that we want to perform is that the user entered a name and that the field isn't blank. We also need a boolean variable that we can set to "true" if any errors are found. Let's now add this variable and the validation code to check if the element has nothing entered.

$(document).ready(function() {

            $("#formsubmit").click(function(event) {

                        var errorsfound = false;

                        var nameinput = $("#name").val();

                        if (nameinput == '')

                        {

                                    $("#verifyname").addClass("error");

                                    errorsfound = true;

                        }

            });

});

We added several statements that check for an input value in the "name" field. The first statement creates a variable we'll use to flag if any errors are found. The second variable gets the value entered into the name field. We only check if a value is entered. You can get much more complex with validation, but remember that users that have JavaScript disabled won't run any client-side script. If you have any validation that is critical before you store the value in your database, it's better to use server-side validation.

If the input value is blank, then we set the span element to the class that displays the text and sets it as red. Red is the standard warning color, but you can set this color to something that matches your color scheme. Since we found an error in the validation, we set the "errorsfound" variable to true. We'll use this boolean variable to stop the form submission, but we haven't coded that part yet.

We have the name input variable validated, and now we need to perform the phone number validation. This is a little more complicated, because we not only want to verify that the user inputs a value, but we also want to verify the format. For basic US phone numbers, we know that they are always 10 digits. They can contain dashes or not, so we need to not only check that input is numeric but we also need to allow dashes. Again, if you want to perform any other validation it's best to perform it on the server side. For instance, you might want to strip dashes and parenthesis values from the input before you save it to a database. You can do this on the server side to ensure that your database has uniform data across all phone number entries. You can then use this uniform input to display phone numbers back to the user with your own formatting code.

You can get complex in your validation, but we are only checking for phone formats such as the following:

            (###) ###-####

            ########## (ten digits)

            ###-###-####

            ### ### ####

            ###.###.####

First, let's copy the original code and then add the validation statements for the phone number.

$(document).ready(function() {

            $("#formsubmit").click(function(event) {

                        var errorsfound = false;

                        var nameinput = $("#name").val();

                        // validate that a name was entered

                        if (nameinput == '')

                        {

                                    $("#verifyname").addClass("error");

                                    errorsfound = true;

                        }

                        // validate the phone number input

                        var pattern = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

                        var phone = $("#phone).val();

                        var isphone = pattern.test(phone);

                        if (!isphone)

                        {

                                    $("#verifyphone").addClass("error");

                                    errorsfound = true;

                        }

            });

});

We introduced a few different statements in the above code. We first created a regex expression variable. We haven't seen this type of variable yet, but know that regex can be a chapter itself. It's a way to match patterns to identify if a string value matches the given pattern. This pattern matches common phone formats, and it can be used to find a matching phone number strings eliminating special characters and letters that would not be included in a standard phone number.

We then use the pattern variable to test the user's input. The phone variable contains the user's input and it's used as the "test" parameter. The test method tests the pattern against the given string (phone) and returns true if there is a match. The method returns false if no pattern match is found.

The "if" statement identifies if the return value is true or false, but notice that there is an exclamation point in front of the boolean variable. The exclamation mark negates the boolean value. If you see an exclamation mark in front of a boolean variable, it changes the value to the opposite one. If the boolean variable contains true, then the exclamation mark tells JavaScript to only run the "if" statements if the variable is "not" true. If the variable contains a false value, the exclamation mark tells JavaScript to run the statements if the value "is" true.

If the user enters a correct phone number, then the statements will not run because the "if" condition will only execute if the phone is "not" true. If the user enters an incorrect phone number, the if statements will run because the variable "is" true. This type of negation condition statements can be confusing at first, so you might need to experiment with this if statement to understand the way it works.

If the user does not enter a correctly formatted phone number, the error message is shown to the user and the "errorsfound" variable is set to true.

We've set up the error messages, but we still haven't managed what happens with the form submission. If the form does not validate, we want to stop it from submitting to the server. If it does validate, we want to submit the form to a processing page.

The following code adds form handling to the function.

$(document).ready(function() {

            $("#formsubmit").click(function(event) {

                        var errorsfound = false;

                        var nameinput = $("#name").val();

                        // validate that a name was entered

                        if (nameinput == '')

                        {

                                    $("#verifyname").addClass("error");

                                    errorsfound = true;

                        }

                        // validate the phone number input

                        var pattern = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

                        var phone = $("#phone).val();

                        var isphone = pattern.test(phone);

                        if (!isphone)

                        {

                                    $("#verifyphone").addClass("error");

                                    errorsfound = true;

                        }

                        if (!errorsfound){

                                    event.preventDefault();

                        }

                        else{

                                    //send form to your chosen processing page

                        }

            });

});

We added one last "if" statement to our code. This "if" statement is what tests the form for errors. Since we've used one boolean variable that contains "true" if any errors are found, then we only need to test this one variable. This is beneficial when you have dozens of form variables to test.

If errors are found, we use the "preventDefault" method to stop the form from submitting. Since we already show the errors, we don't need to do anything else. The "else" statement is what forwards the data to a processing page. You can add a processing page to the "action" property in the form element, or you can use an AJAX method to post the data. What you choose is dependent on the way you want to handle your form submission. If you want to use asynchronous submissions, then you use AJAX and the page will not reload. If you submit directly to the processing page, then the browser sends the data and reloads a new page.

That's all you need in your code. For simplicity, the following is a copy of all jQuery code plus the HTML page so that you can copy and paste it.

<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js">></script>

<style>

            .error {

            display: none;

            margin-left: 20px;

            }                      

            .showerror {

            color: red;

            margin-left: 20px;

            }

</style>

<script>

$(document).ready(function() {

            $("#formsubmit").click(function(event) {

                        var errorsfound = false;

                        var nameinput = $("#name").val();

                        // validate that a name was entered

                        if (nameinput == '')

                        {

                                    $("#verifyname").addClass("error");

                                    errorsfound = true;

                        }

                        // validate the phone number input

                        var pattern = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

                        var phone = $("#phone).val();

                        var isphone = pattern.test(phone);

                        if (!isphone)

                        {

                                    $("#verifyphone").addClass("error");

                                    errorsfound = true;

                        }

                        if (!errorsfound){

                                    event.preventDefault();

                        }

                        else{

                                    //send form to your chosen processing page

                        }

            });

});

</script>

</head>

<body>

<div id="inputform">

            <form id="contactinfo" method="post" action="">

            <!-- Name -->

            <div>

                        <label for="name">Name:</label>

                        <input type="text" id="name" name="name"></input>

                        <span style="display: none" id="verifyname">This field is required</span>

            </div>

            <!-- Phone -->

            <div>

                        <label for="phone">Email:</label>

                        <input type="text" id="phone" name="phone"></input>

                        <span style="display: none" id="verifyphone">A valid phone number is required</span>                                               

            </div>

            <div id="submitcontainer">                                               

                        <button type="submit" id="formsubmit">Submit</button>

            </div>

            </form>

</div>

</body>

</html>

Form validation is another advantage you have with jQuery. You can reduce overhead on your web server, speed up form submissions, and instantly let your users know if they've missed any input on your page.