Many times you want to verify, as best you can, that the user filled out an online form properly before it is submitted.

With JavaScript and jQuery, you can check that fields have been entered in the correct format. You can also check that required fields have been filled out. Once the verification process has be finished, you can alert the user that a certain field has not been filled out or is in an improper format.

Keep in mind that JavaScript is a client-side program and the form must acually be submitted to the server using a program like PHP, but you can use JavaScript and jQuery to verify the format prior to submitting the form.

There are also other free form program creators on the internet. Its a good idea to have a basic understanding of how the fields are being validated for troubleshooting purposes.

This tutorial will create a simple form. If the user uses the correct format, the information will be placed into the fields below - this is simulating a separate file where the information would go if this were a live form. If the user fails to complete a field, the line will turn red to let him know which fields have been left blank. If the user uses the wrong format for the information, a statement will appear to let him know what was done incorrectly.

Tutorial-9 uses many jQuery methods, including: .val(), .closest(), .html(), .parent(), .next(), .css() and .focus()

 

jquery-blank.html

Create a new document: tutorial-10.html

We will start out with the basic jQuery document that was created in Tutorial 1.

Open up the document called jquery-blank.html in a text editor and do a "Save As" into the same directory. Save the document as  tutorial-10.html.


Create the HTML elements

Inside of the <body>...</body> tags we are going to create a fairly simple form. This is just a demo form and the information is not submitted across the internet.

Type (or copy and paste) the following into your open document:

<body>
<div id="container">
<form name="infoReq" id="infoReq">
<table>
<tbody>
<tr>
    <td><label for="fName" class="formLabel">First Name:</td>
    <td><input name="fName" type="text" id="fName" size="30"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="lName" class="formLabel">Last Name:</td>
    <td><input name="lName" type="text" id="lName" size="30"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="email" class="formLabel">Email:</td>
    <td><input name="email" type="text" id="email" size="30"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="phone" class="formLabel">Phone:</td>
    <td><input name="phone" type="text" id="phone" size="30"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="city" class="formLabel">City:</td>
    <td><input name="city" type="text" id="city" size="30"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="state" class="formLabel">State:</td>
    <td><input name="state" type="text" id="state" size="4"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td><label for="zip" class="formLabel">Zip:</td>
    <td><input name="zip" type="text" id="zip" size="15"></td>
    <td class="checkIt"></td>
</tr>
<tr>
    <td></td>
    <td id="notFilledWarning" ></td>
    <td id="submitArea"><input name="submit" type="button" id="submitButton" value="Submit"></td>
</tr>
</tbody>
</table>
</form>
<div id="finalInfo">
<table>
<tbody>
<tr>
    <td><label for="fName" class="formLabel">First Name:</td>
    <td id="fNameFinal"></td>
</tr>
<tr>
    <td><label for="lName" class="formLabel">Last Name:</td>
    <td id="lNameFinal"></td>
</tr>
<tr>
    <td><label for="email" class="formLabel">Email Address:</td>
    <td id="emailFinal"></td>
</tr>
<tr>
    <td><label for="phone" class="formLabel">Contact Phone:</td>
    <td id="phoneFinal"></td>
</tr>
<tr>
    <td><label for="city" class="formLabel">City:</td>
    <td id="cityFinal"></td>
</tr>
<tr>
    <td><label for="state" class="formLabel">State:</td>
    <td id="stateFinal"></td>
</tr>
<tr>
    <td><label for="zip" class="formLabel">Zip:</td>
    <td id="zipFinal"></td>
</tr>
<tr>
    <td style="font-size: .8em;border-top: 1px solid #555; font-style: italic;color: #555;" colspan="2">Note: This form is a demo only and the information is not sent over the internet.</td>
</tr>
</tbody>
</table>
</div>
<input type="button" name="refresh" id="refresh" value="REFRESH PAGE" />
</div><!-- END container -->
</body>


Style the HTML element

Let's add some styling to create the container to hold it all, the box for the visitor to click and then place the balloons out of sight. Above the closing </head> tag, you will see the <style type="text/css">...</style> section. Add the following:

<style type="text/css">
    body {font-family: Arial, sans-serif;background: url(../sitegraphics/jqz-demo.jpg)}
    #container {width: 500px; height: 500px; margin: 0 auto;background: #fff;padding: 20px;}
    #infoReq table {width: 100%; margin: 0 auto;background: #eeffee;border: 1px #ccc solid;
    border-collapse: collapse;}
    #infoReq table tr {}
    #infoReq table td {border-bottom: 1px #ccc solid;padding: 5px;}
    #infoReq table td:first-child {width: 100px;}
    #infoReq table td.checkIt {color: #990000; font-style: italic; font-size: .9em;
    width: 150px;}
    td#submitArea {text-align: right;}
    input[type=text] {background-color: #eee;border: 1px #999 solid;
    box-shadow: inset 0 0 2px rgba(0,0,0,.2)}
    input:focus {background-color: #fff;}
    #finalInfo td {padding-right: 10px;}
</style>


Add the jquery code

Go up to the <script>...</script> section in the <head>...</head> section. This is the section with $(document).ready() function already inserted.

Or put the jQuery script into a separate document

You can also choose to place this lengthy script into an external .js file in your js folder. If so, in the external file, save all but the <script> and closing </script> tags into a file named tutorial-9.js. Then put this line into the <head> section of your HTML document:

<script type="text/javascript" src="/js/tutorial-9.js" ></script>

<script type="text/javascript">
    $(document).ready(function(){
        $("input:text").each(function() {
            $(this).val("");
        });

        $("#fName").focus();
        $("#submitButton").click(function(){

            /****VERIFY FIRST NAME***/
            var fName = $("#fName").val();
            if (fName == "") {
                $("#fName").closest("tr").css("background-color","#ffdddd");
                $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
            } else {
                if (checkTextOnly(fName)){
                $("#fNameFinal").html(fName);
                $("#fName").parent().next().html("");
            } else {
               $("#fName").parent().next().html("Enter letters only");
            }
            }

            /****VERIFY LAST NAME***/
            var lName = $("#lName").val();
            if (lName == "") {
                $("#lName").closest("tr").css("background-color","#ffdddd");
                $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
            } else {
                if (checkTextOnly(lName)){
                $("#lNameFinal").html(lName);
                $("#lName").parent().next().html("");
           } else {
               $("#lName").parent().next().html("Enter letters only");
           }
        }

        /****VERIFY EMAIL***/
        var email = $("#email").val();
        if (email == "") {
            $("#email").closest("tr").css("background-color","#ffdddd");
            $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
        } else {
            if (emailaddressOnly(email)){
            $("#emailFinal").html(email);
            $("#email").parent().next().html("");
        } else {
            $("#email").parent().next().html("Check email address");
        }
    }

        /****VERIFY PHONE***/
        var phone = $("#phone").val();
        if (phone == "") {
            $("#phone").closest("tr").css("background-color","#ffdddd");
            $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
        } else {
            if (phoneAmericanOnly(phone)){
                $("#phoneFinal").html(phone);
                $("#phone").parent().next().html("");
        } else {
            $("#phone").parent().next().html("Format: 222-222-2222");
        }
        }

        /****VERIFY CITY***/
        var city = $("#city").val();
        if (city == "") {
            $("#city").closest("tr").css("background-color","#ffdddd");
            $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
        } else {
            if (checkTextOnly(city)){
                $("#cityFinal").html(city);
                $("#city").parent().next().html("");
        } else {
            $("#city").parent().next().html("Enter letters only");
        }
        }
        /****VERIFY STATE***/
        var state = $("#state").val();
        if (state == "") {
            $("#state").closest("tr").css("background-color","#ffdddd");
            $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
        } else {
            if (usStateOnly(state)){
            $("#stateFinal").html(state);
            $("#state").parent().next().html("");
        } else {
            $("#state").parent().next().html("Format: OR");
        }
        }
        /****VERIFY ZIP***/
        var zip = $("#zip").val();
        if (zip == "") {
            $("#zip").closest("tr").css("background-color","#ffdddd");
            $("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");
        } else {
            if (zipAmericanOnly(zip)){
                $("#zipFinal").html(zip);
                $("#zip").parent().next().html("");
        } else {
            $("#zip").parent().next().html("Format: 88888 or 88888-8794");
        }
        }
    });//END submit button

function checkTextOnly(phrase){
    var textOnly = /[A-Za-z]+/;
    var result = textOnly.test(phrase);
    return result;
}

function emailaddressOnly(phrase){
    var emailOnly = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
    var result = emailOnly.test(phrase);
    return result;
}

function phoneAmericanOnly(phrase){
    var phoneOnly = /^\d{3}-\d{3}-\d{4}$/;
    var result = phoneOnly.test(phrase);
    return result;
}

function usStateOnly(phrase){
    var stateOnly = /^((A[LKSZR])|(C[AOT])|(D[EC])|(F[ML])|(G[AU])|(HI)|(I[DLNA])|(K[SY])|(LA)|(M[EHDAINSOT])|(N[EVHJMYCD])|(MP)|(O[HKR])|(P[WAR])|(RI)|(S[CD])|(T[NX])|(UT)|(V[TIA])|(W[AVIY]))$/;
    var result = stateOnly.test(phrase);
    return result;
}

function zipAmericanOnly(phrase){
    var zipOnly = /^\d{5}(?:[-\s]\d{4})?$/;
    var result = zipOnly.test(phrase);
    return result;
}

$("#refresh").click(function() {
    location.reload();
}); // END submit
       
    });  // End document.ready()
</script>


Let's go thru the script:

$("input:text").each(function() {

this uses the .each() method to iterate through each <input type="text"> tag.

$(this).val("");

this uses the .val() method to clear all the input fields

});

close the .each() function

$("#fName").focus();

this uses the .focus() method to put the blinking cursor into the first form field. The CSS for this page changes whatever field has the focus to white.

$("#submitButton").click(function(){

we chose too use an <input type="button"> for this tutorial rather than the .submit() method. The .click() method will not instantly clear the fields as does .submit().

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

retrieve the information that the user typed into the <input id="#fName"> field and assign it to the variable fName

if (fName == "") {

use a comparison operator of == to test if any information was left blank. If so, do the following steps

$("#fName").closest("tr").css("background-color","#ffdddd");

this step uses the .closest() method to find the next <tr> tag in the DOM tree. It then uses .css() to color the background of the entire row to alert the user which field was not completed.

$("#notFilledWarning").css("background-color","#ffdddd").html("All fields must be completed");

There is also a warning box at the bottom of the form that explains the reason the empty fields were highlighted.

} else  {

if the field was not left blank, move on to these other steps

if (checkTextOnly(fName)){

we are calling the function of checkTextOnly(), which is defined later in the script, and passing the value of fName to it for the function to evaluate for the correct format. If the value is in the correct format, the function returns true.

 $("#fNameFinal").html(fName);

if the statement in the prior step is true, place the name in the box below the form. This tutorial is putting the information right back on the page. In a real form, there would be a step to process this information and send it to the server.

$("#fName").parent().next().html("");

The next <td> past the one with #fName is where the warning phrase is placed. If the user used the right format, we are assuring that this box is blank.

 } else { 

if the validation is not the proper format - the function checkTextOnly() will return a value of false, so proceed with the following step.

$("#fName").parent().next().html("Enter letters only");

enter the warning phrase into the next box. Since the <input id="fName"> is inside the <td> we need to go up a step to its .parent() then go to the .next() sibling then put in the .html()

close the last else statement

close the prior else statement

...

the program goes through each of the field in a similar manner, but each field will have different id numbers and may call other functions to check for a proper email address, US State, zip code and phone number format.

...

lets go through a couple of the functions that use regular expressions to test the format of the value retrieved from the input.

function checkTextOnly(phrase){

this is creating a function that is used for the fName, lName and City fields. It is checking that no numbers were used in the field. The word phrase simple will be the variable that holds the value that was passed to the function. Since this function is being used for several different values, we did not want to be too specific with this term for the parameter.

var textOnly = /[A-Za-z]+/;

this is using a regular expression that tests if the characters are in the range of A-Z or a-z. The regular expression is placed between forward slashes. The plus sign is used to allow for multiple characters.

var result = textOnly.test(phrase);

when testing for a regular expression, use .test(). This will return true if the phrase matches the pattern of the regular expression.

return result;

this is the value that the function will return when called, true or false.

}

close the function

...

there are separate functions that use regular expressions for the email address, phone number, zip code and state abbreviation.


Test the code

Save the document and open up a new browser window. Type the path to the document in the address bar of the browser. For example:

file:///C:/jquery-tutorials/tutorial-10.html

When you open up the document, you should see something like this.