Form Validation with JavaScript

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 validation
Client-side form validation (usually with JavaScript embedded in the Web page)
Server-side validation
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.

Open this page to see it in action. Try pressing the Send Details button without filling anything in the "Your Name" field.

You might like to open the source code for this form in a separate window, so that you can refer to it throughout the tutorial.

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:

<form name="contact_form" method="post"
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'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:

<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>


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:

<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;


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:

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:

    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:

    return valid;

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




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.

Open this page to see it in action. Try pressing the Send Details button without filling in the form and see what happens.

Again, you might like to open the source code for this form in a separate window, so that you can refer to it as we talk you through.

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:

    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:

    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:

    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.

An exercise: "one field at a time" validation

Our example script works by validating all the form fields at once. This can be a bit confusing for the user, especially if they've missed out more than one field, as they will get lots of alert boxes appearing and they might forget which fields they need to fill in!

As an exercise, try modifying the script to only prompt the user one field at a time. For example, if they miss out the "Name" and "Gender" fields and press "Send Details", it will only prompt them for the "Name" field initially. Then, after they fill in the "Name" field and press "Send Details" again, it will prompt them for the "Gender" field.

As a finishing touch, try making the script move the cursor to the field that needs filling in each time (Hint: use the focus() method to do this).

Good luck!

Follow Elated

Related articles

Responses to this article

20 most recent responses (oldest first):

16-Feb-11 13:44
I'm hoping you can provide me with some guidance. I have a registraion form setup with javascript validation in place, but there is one place I'm having trouble. I have a dropdown selection list, and based on the selection, there are text fields that are hidden or displayed for more info. So if you select the second item in the drop down, a text field associated with that selection appears. My issue is how to make that text field required, but only required based on drop down selection. I know there are ways to do this with radio buttons and checkboxes, but can it be done with dropdowns as well? The form is large so I didn't want to paste all here, but the snap shot of the items I'm referring to are:

<tr><td colspan=2 width="525" align="center">
<a class="form">Please let us know how you learned about us.<br></a></td></tr>
<td colspan=2 width="525" align="center" class="form">
<select id="dropdown1" name="dropdown" onchange="display(this,'Google Search','Yahoo Search','Bing Search');" size="1" style="width:320px; font-size:11px; font-weight: bold; color: #686363;">
<option>Please select:</option>
<option value="Google Search">Google Search</option>
<option value="Yahoo Search">Yahoo Search</option>
<option value="Bing Search">Bing Search</option>
<option value="Other">Other</option>

<tbody id="Google Search" style="display: none;">
<td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
<td class="field"><br>
<input type="hidden" class="tbox1" id="textfield14" name="googlekey" size="40" value="-" />
<input type="text" class="tbox1" id="textfield14" name="googlekey" size="40" value="" /></td>

<tbody id="Yahoo Search" style="display: none;">
<td class="form" align="right"><br><br>Keywords used for search <font color="red">(Required)</font>:&nbsp;&nbsp;</td>
<td class="field"><br>
<input type="hidden" class="tbox1" id="textfield15" name="yahookey" size="40" value="-" />
<input type="text" class="tbox1" id="textfield15" name="yahookey" size="40" value="" /></td>

Is it possible to make the the text field with name=googlekey required if some selects Google Search in drop down...but not required if they make some other selection? Thanks, David

[Edited by catron on 16-Feb-11 13:51]
20-Feb-11 19:14
@jjj84: Great stuff.

@catron: Yes, you could write something like:

if ( document.contact_form.dropdown.selectedIndex == 1 && document.contact_form.googlekey.value == "" )
alert ( "Please fill in the googlekey field" );
valid = false;
23-Feb-11 08:44
im having trouble with my student registration form..

if you choose the subjects BSIT, BSMATH,BSED,BEED..the year level will be limited until 4 year only while if course is BSCE,BSGE,BSArch it will limit until 5 year.. how to validate it?? can anyone help me.. thanks in advance...

<table cellpadding="10" cellspacing="10" style="text-align:left;margin-left:15em" >
<td>User Name</td>
<td><input name="uname" type="text" id="uname" onKeyUp="isalphanum(this)" value="" size="16"/></td>

<td><input type="text" name="password" value="" size="16" onKeyUp="isalphanum(this)" /></td>
<td>Id No. </td>
<td><input name="idno" type="text" id="idno" onkeyup="isnum(this)" value="" size="8" /></td>
<td><input name="name" type="text" id="name" onkeyup="isalpha(this)" value="" size="16" /></td>
<select name="course" id="course" >
<option value="BSIT">BSIT</option>
<option value="BSMATH">BSMATH</option>
<option value="BSED">BSED</option>
<option value="BEED">BEED</option>
<option value="BSPSYCH">BSPSYCH</option>
<option value="BLIS">BLIS</option>
<option value="BSCE">BSCE</option>
<option value="BSGE">BSGE</option>
<option value="BSArch">BSArch</option>
<td><input name="year" type="text" id="year" onkeyup="isnum(this)" value="" size="8" /></td>
28-Feb-11 04:24
@pakits: Please post your question in a new topic:
20-Apr-11 10:05
Hi, and thanks for all of the examples. I am writing a script that validates two select menus. Could you please give me an example of how to check them one at a time and how to concatonate the errors if they exist?
25-Apr-11 02:20
@jhollender: "Validating drop-down lists" in the article shows how to check if a user has selected an option in a select menu.

To concatenate the error messages, use "+". For example:

errorMessage += "Please select your Age.\n"
25-Apr-11 23:15

Thanks for your codes. I am trying to validate "surname" in a form.

I need to check that it is not "empty" and if not they are alpha characters with -, space and ' special characters and with a limit of 30 chars.

The name of my form is "myForm"

I have not been able to find code anywhere that incorporates the 2 (That is, empty or alpha).

The name of the function is validateForm()
28-Apr-11 06:54
@ElizaKaye: Something like this should do what you need (I haven't tested it mind!):

if ( !document.contact_form.surname.value.match( /^[a-zA-Z- ']+$/ ) || document.contact_form.surname.value.length > 30 ) {
alert ( "Please enter your surname." );
valid = false;

You'll need to put that inside your validate_form() function.

06-Jul-11 10:45
Very useful. I recently stumbled across where i found a simple JavaScript validation form for beginners. I hope this will help some beginners.
01-Aug-11 02:51

Looking for a solution to trapping the space being entered.

[code]if ( document.contact_form.contact_name.value == "" )
alert ( "Please fill in the 'Your Name' box." );
valid = false;
} [code]
In your example if one enters [] [] [] it does not trap it.

How would you stop just spaces being entered.
08-Aug-11 07:39
@peterfc2: Try the '===' operator instead of '=='.
05-Nov-11 10:44
Thanks for the information! I get my form to work with the validation, but everyone who first submits the form gets this error: "403 No variable substitutions in template"
When you reload the page the form sends perfectly. ??? I cant figure that out.
Please help!
07-Nov-11 00:37
07-Nov-11 00:49
Thanks for the reply - It is a cgi script: It was only after deleting my browser history that a correction in my template.txt works for me. All fine thanks for the good article.
02-Dec-11 10:18

If I have this code :

function validation(){

valid = true;

if ( ==""){

alert("Please enter your name");
valid = false;
if (document.myForm.lastname.value ==""){

alert("Please enter your lastname");
valid = false;
if (document.myForm.address.value ==""){

alert("Please enter your address");
valid = false;

return valid;

How can I show all the form validation errors together in a message box ?
06-Dec-11 02:03
@Shone: Rather than using alert()s for each field, just concatenate the error messages together into a string (separated by e.g. "\n"), then display the final string in an alert box if valid == false.
22-Dec-11 04:44
I have a problem with my form. It has three fields which I want to validate but in testing it the first incident of validation causes the alert to pop up but then when I click OK on the alert it submits the form anyway without letting me complete the field and continue to the other fields.
It can be found at;
18-Jan-12 20:46
Hi Matt,

I find your site very helpful.
I am an ms access guy and very new to javascript, I am trying an web application with php & mysql.

Need help for js validation in my school project.

Tablename : Table1
Feilds : Name, Class, CheckboxBook1, CheckboxBook2

Example Data:-

Name: gary Class: 1A
jane 1A
sree 1B
rita 1B
jai 1B

Validation : Each class can only select not more than 2 of Book1 and 2 of Book2

Please give me the code .

Thanking you.
08-Mar-12 17:21
Thank you for the great code! Validation is working when I test the forms but I am getting emails with 1 or -1 in fields (instead of a valid phone or email, etc.) AND I am getting 20, 40, 80 at one time.

I have tried to enter a 1 or -1 and it gives me the appropriate error message so I am not sure how I am getting these emails.

Can you give me an idea where to look / what I should do to stop these form submissions since they have gotten around the validation.

09-Mar-12 18:13
@tracie: Sounds like a problem with your form-to-email script running on your server, rather than a JavaScript problem.

View all 64 responses »

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page