/beyond/article.php/3849281/Checking-Your-Work-Validating-Input----Getting-Started.htm Checking Your Work: Validating Input -- Getting Started

Checking Your Work: Validating Input -- Getting Started

By Curtis Dicken

Introduction to Validating Using JavaScript

Whether you are accepting input for something as simple as a guestbook or something as complex as an employment application, it makes sense to check the user’s input before committing it to a database or even an email. There are two basic types of validation: server-side and client-side. In this series we will be exploring client-side validation using JavaScript. While client-side validation is not as secure as server-side validation, it does not require a roundtrip to the server. This means that validation occurs quickly and does not cause the page to reload or send anything to the server.

Creating a Test Form

For our example we will be using something simple and practical; a guestbook. Below is the HTML for our form. We have included very specific HTML input elements in order to demonstrate our different validation concepts to follow.


    <title>Guestbook Validation Example</title>



<form onsubmit='return validateMyForm()'>

    First Name:

    <input id="TextFirstName" type="text" /><br />

    Last Name:

    <input id="TextLastName" type="text" /><br />


    <input id="TextTelephone" type="text" /><br />


    <input id="TextEmail" type="text" /><br />


    <select id="SelectCountry">

        <option value="Select your country..." selected="selected">Select your country...</option>

        <option value="Canada">Canada</option>

        <option value="France">France</option>

        <option value="United Kingdom">United Kingdom</option>

        <option value="United States">United States</option>    </select>

    <br />

    How many years have you been using the internet?

    <input id="TextInternetYears" type="text" /><br />

    Add to mailing list?

    <input id="RadioMailingListYes" type="radio" name="MailingList" checked="checked" />


    <input id="RadioMailingListNo" type="radio" name="MailingList" />

    No<br />

    Favorite websites?

    <input id="CheckboxHtmlGoodies" type="checkbox" />


    <input id="CheckboxWDVL" type="checkbox" />


    <input id="CheckboxInternet" type="checkbox" />


    <input id="CheckboxJavaScript" type="checkbox" />


    <input id="CheckboxNone" type="checkbox" />

    None<br />

    <br />

    <input id="ButtonSubmit" type="button" value="Submit" />




Required Input

Our first step will be to confirm that the user has completed everything required on the form. For the purposes of this example we are keeping it simple and making everything required. However, before we can begin validating we need to create a JavaScript function that handles all of our validation. If you noticed, we have already given that function a name in our form tag above, validateMyForm.

We’ll start simple by making sure that the user has entered something in the first name, last name, telephone, email, and number of years fields using the internet text boxes. Here’s the code:

<script type="text/javascript">


    function validateMyForm()


        // Create validation tracking variables

        var valid = true;

        var validationMessage = 'Please correct the following errors:\r\n';


        // Validate first name

        if (document.getElementById('TextFirstName').value.length == 0)


            validationMessage = validationMessage + '  - First name is missing\r\n';

            valid = false;



        // Validate last name

        if (document.getElementById('TextLastName').value.length == 0)


            validationMessage = validationMessage + '  - Last name is missing\r\n';

            valid = false;



        // Validate telephone

        if (document.getElementById('TextTelephone').value.length == 0)


            validationMessage = validationMessage + '  - Telephone is missing\r\n';

            valid = false;



        // Validate email

        if (document.getElementById('TextEmail').value.length == 0)


            validationMessage = validationMessage + '  - Email is missing\r\n';

            valid = false;



        // Validate years on internet

        if (document.getElementById('TextInternetYears').value.length == 0)


            validationMessage = validationMessage + '  - Years using internet is missing\r\n';

            valid = false;



        // Display alert box with errors if any errors found

        if (valid == false)





        return valid;




Our first order of business in our validation function is to create two variables. The first, valid, keeps track of whether or not we have found any invalid input. We assume everything is good to start with by setting valid to true. If any validation errors occur we’ll change valid to false. Setting valid to false when we find an error accomplishes two purposes:
  1. We return the false value which keeps the form from completing its designated action.
  2. We use the value to determine whether we need to fire the validation message box.
Next we create validationMessage which we will use to build our validation error message for our message box. Note the “\r” and “\n” which gives us a return and new line in our message box.

Now we can simply step through each element that we need to validate and perform the appropriate checks. To validate each element we use the document.getElementById('MyElementName') to find the element and validate its value. To see if the user has entered a value we check to see if the length of the text box is greater than 0.

Once we have completed all of our validation checks, we use valid to see if we found any errors along the way. If we did, we fire the message box with the message text we have been building in validationMessage.

Required Input – Dropdown List Box Style

Now that we have our structure for validation in place we can move on down the form and add whatever additional validation we need. We next want to make sure that something other than the default selection for country has been chosen. Accomplishing this is simply a matter of comparing the selected value with the default value. If they are the same, we flag it as a validation error, otherwise we are good to go. Here is the code we would add just before if (valid == false):
// Validate coutry selected

        if (document.getElementById('SelectCountry').value == 'Select your country...')


            validationMessage = validationMessage + '  - Please select your country\r\n';

            valid = false;


Adding Error Messages to the Form

While the validation message box is a great way to inform the user of errors, it is also helpful to provide an indicator on the form itself. This lets the user easily find mistakes they need to change once they have closed the message box. To accomplish this we use span to place an invisible error message on the form. We’ll use the first name text box for this example. Change the following:
<input id="TextFirstName" type="text" /><br />
To look like:
<input id="TextFirstName" type="text" /><span id="errorFirstNameMissing" style="visibility:hidden;">*Please provide your first name.</span><br />
Now that we have our message in place we toggle the message on whenever we need using a little JavaScript. Change the section of code that validates the first name to look like this:
// Validate first name

        if (document.getElementById('TextFirstName').value.length == 0)


            validationMessage = validationMessage + '  - First name is missing\r\n';


            valid = false;






More to Come

As you can see validating is not terribly difficult. Mostly it’s just time consuming and occasionally tedious. Obviously, the code examples above could easily be condensed into separate functions to handle checking length and toggling the in-form error messages. In order to make this a better teaching tool I opted to do it the long way. In the next and final installment of this series we’ll get into some of the more interesting stuff. We’ll make sure at least one of our example check boxes has been checked, confirm we have a properly formatted email address and telephone number, and check our number of years using the internet is an integer.

Happy validating!

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date