How to do Form Validation with JavaScript

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to do Form Validation with JavaScript

Post by Neo » Mon Mar 01, 2010 10:42 am

Shows you how to write a script that ensures your form is filled in correctly before it's sent to your server. Great for "required fields" such as email addresses!

This tutorial will show you how to create a JavaScript-enabled form that checks whether a user has filled in the form correctly before it's sent to the server. This is called form validation. First we'll explain why form validation is a useful thing, and then build up a simple example form, explaining things as we go along. At the end, there's a little exercise to keep you busy too!

What is form validation?
Form validation is the process of checking that a form has been filled in correctly before it is processed. For example, if your form has a box for the user to type their email address, you might want your form handler to check that they've filled in their address before you deal with the rest of the form.

There are two main methods for validating forms: server-side (using CGI scripts, ASP, etc), and client-side (usually done using JavaScript). Server-side validation is more secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to do and quicker too (the browser doesn't have to connect to the server to validate the form, so the user finds out instantly if they've missed out that required field!).
client_side.gif
client_side.gif (6.02 KiB) Viewed 2936 times
Client-side form validation (usually with JavaScript embedded in the Web page)
server_side.gif
server_side.gif (6.02 KiB) Viewed 2936 times
Server-side form validation (usually performed by a CGI or ASP script)

In this tutorial we'll build a simple form with client-side JavaScript validation. You can then adapt this form to your own requirements.

A simple form with validation
Let's build a simple form with a validation script. The form will include one text field called "Your Name", and a submit button. Our validation script will ensure that the user enters their name before the form is sent to the server.

Following is the sample source code with a simple form.

Code: Select all

<html>

<head>

<title>A Simple Form with JavaScript Validation</title>

<script type="text/javascript">

<!--

function validate_form ( )
{
    valid = true;

        if ( document.contact_form.contact_name.value == "" )
        {
                alert ( "Please fill in the 'Your Name' box." );
                valid = false;
        }

        return valid;
}

//-->

</script>

</head>

<body bgcolor="#FFFFFF">

<form name="contact_form" method="post"
action="/cgi-bin/articles/development/javascript/form-validation-with-javascript/contact_simple.cgi"
onSubmit="return validate_form ( );">

<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>

</form>

</body>

</html>
You can see that the page consists of a JavaScript function called validate_form() that performs the form validation, followed by the form itself. Let's look at the form first.

The form
The first part of the form is the form tag:

Code: Select all

<form name="contact_form" method="post"
action="/cgi-bin/articles/development/
  javascript/form-validation-with-javascript/contact_simple.cgi"
onsubmit="return validate_form ( );"> 
The form is given a name of "contact_form". This is so that we can reference the form by name from our JavaScript validation function.

The form uses the post method to send the data off to a dummy CGI script on ELATED.com's server that thanks the user. In reality, you would of course send the data to your own CGI script, ASP page, etc. (e.g. a form mailer).

Finally, the form tag includes an onsubmit attribute to call our JavaScript validation function, validate_form(), when the "Send Details" button is pressed. The return allows us to return the value true or false from our function to the browser, where true means "carry on and send the form to the server", and false means "don't send the form". This means that we can prevent the form from being sent if the user hasn't filled it in properly.

The rest of the form prompts the user to enter their name into a form field called contact_name, and adds a "Send Details" submit button:

Code: Select all

<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>

</form> 
Now let's take a look at the JavaScript form validation function that does the actual work of checking our form.

The validate_form() function
The form validation function, validate_form(), is embedded in the head element near the top of the page:

Code: Select all

<script type="text/javascript">
<!--

function validate_form ( )
{
    valid = true;

    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    }

    return valid;
}

//-->
</script>
The first line (<script type="text/javascript">) tells the browser that we are writing some JavaScript, and the HTML comment (<!--) in the second line hides the script from older browsers that don't understand JavaScript.

Next we start our validate_form() function, then set a variable called valid to the value true:

Code: Select all

function validate_form ( )
{
    valid = true; 
We use this valid variable to keep track of whether our form has been filled out correctly. If one of our checks fails, we'll set valid to false so that the form won't be sent.

The next 5 lines check the value of our contact_name field to make sure it has been filled in:

Code: Select all

    if ( document.contact_form.contact_name.value == "" )
    {
        alert ( "Please fill in the 'Your Name' box." );
        valid = false;
    } 
If the field is empty, the user is warned with an alert box, and the variable valid is set to false.

Next, we return the value of our valid variable to the onSubmit event handler (described above). If the value is true then the form will be sent to the server; if it's false then the form will not be sent:

Code: Select all

    return valid; 
Finally, we finish our validate_form() function with a closing brace, and end our HTML comment and script element:

Code: Select all

}

//-->

</script>
That's all there is to simple JavaScript form validation! Our example is very simple as it only checks one field. Let's expand this example with a more complex function that checks lots of form fields. We'll also look at how to check other types of fields, such as checkboxes, radio buttons and drop-down lists.

A more complex form
Let's look at a more complex validated form with some different types of form fields.

See following code for the source code.

Code: Select all

<html>

<head>

<title>A Simple Form with JavaScript Validation</title>

<script type="text/javascript">

<!--

function validate_form ( )
{
    valid = true;

        if ( document.contact_form.contact_name.value == "" )
        {
                alert ( "Please fill in the 'Your Name' box." );
                valid = false;
        }

        return valid;
}

//-->

</script>

</head>

<body bgcolor="#FFFFFF">

<form name="contact_form" method="post"
action="/cgi-bin/articles/development/javascript/form-validation-with-javascript/contact_simple.cgi"
onSubmit="return validate_form ( );">

<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>
<p><input type="submit" name="send" value="Send Details"></p>

</form>

</body>

</html>
Like our previous example, this page has a form called contact_form and a function called validate_form(). In addition to the previous text field, the form has radio buttons, a drop-down list and a checkbox.

The validate_form() function now has 3 extra checks, one for each of our new fields.

Validating radio buttons
After the contact_name text box has been checked, the gender radio buttons are validated:

Code: Select all

    if ( ( document.contact_form.gender[0].checked == false )
    && ( document.contact_form.gender[1].checked == false ) )
    {
        alert ( "Please choose your Gender: Male or Female" );
        valid = false;
    } 
This code checks to see whether either of the radio buttons ("Male" or "Female") have been clicked. If neither have been clicked (checked == false), the user is alerted and valid is set to false.

Validating drop-down lists
Next the "Age" drop-down list is checked to see if the user has selected an option. In the form, we named the first option in the drop-down list "Please Select an Option". Our JavaScript can then check which option was selected when the user submitted the form. If the first option is selected, we know the user has not selected a "real" option and can alert them:

Code: Select all

    if ( document.contact_form.age.selectedIndex == 0 )
    {
        alert ( "Please select your Age." );
        valid = false;
    } 
Note that the values for selectedIndex start at zero (for the first option).

Validating checkboxes
Finally, the "Terms and Conditions" checkbox is validated. We want to the user to agree to our imaginary Terms and Conditions before they send the form, so we'll check to make sure they've clicked the checkbox:

Code: Select all

    if ( document.contact_form.terms.checked == false )
    {
        alert ( "Please check the Terms & Conditions box." );
        valid = false;
    } 
Because we set our valid variable to false in any one of the above cases, if one or more of our checks fail, the form will not be sent to the server. If the user has not completed more than one field, then they will see an alert box appear for each field that is missing.

Now you know how to write a form validation script that can handle multiple form fields, including text boxes, radio buttons, drop-down lists and check boxes!

One point to note about JavaScript validation is that it can always be circumvented by the user disabling JavaScript in their browser, so for secure validation you'll need to write your validating code in your server-side scripts. However, for day-to-day use JavaScript is a quick and easy way to check over your forms before they're sent to your server.
Post Reply

Return to “Web programming”