Form Validation

21.9.2006, 21:27
Submited in: JavaScript | Total Views: 35023

Before sending data from script form it is necessarily to check input date. JavaScript is ideal for that, because the all date befor submitting, will be checked and by that we will save on bandwith.

In this tutorial we'll show you how to create a validation forms on particular example.

We will create a form for 4 fields
- Name and Surname
- Email
- Age
- Gender

<form action="action.asp" method="post" name="myform">

Name and Surname: <br/>
<input type="text" name="nameandsurname" size="30"> <br/>

Email: <br/>
<input type="text" name="email" size="30"> <br/>

Age: <br/>
<input type="text" name="age" size="3"> <br/>

Gender: <br/>
<select size="1" name="gender">
<option>- Select gender -</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select> <br/>

<input type="submit" value="Submit" onClick="check();return false;">


On submit button, we have set check function that will test if the all date are entered and are they correct, on click.

Check function () will check are the two words with space within entered in fields name and surname.

E-mail adress must contain symbols "@"  and ".", but they must not contain a space.
Field Age must be positive number.

From Gender menu you must choose a gender.
based on our Html form, our JavaScript function for check will look like this:

JavaScript Function
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

function check() {

var nameandsurname = document.myform.nameandsurname;
var email =;
var age = document.myform.age;
var gender = document.myform.gender;

if ( nameandsurname.value.indexOf(" ") == -1) {
alert("Enter your Name and Surname.");

} else if ((email.value.indexOf("@") == -1) || (email.value.indexOf(".") == -1)) {
alert("Enter your valid email address.");

} else if (! (parseInt(age.value) > 0)) {
alert("Enter your Age.");

} else if (gender.selectedIndex == 0) {
alert("Select your gender.");

} else {




Put this javascript code between your <head> </head> tags.

At the start of our function the references are saved in variable on fields element in our form.
First "if block" checks are the name and surname fields contain space.

In another "if block", e-mail adress is checked in an similar way.

In another "block" (third block)  valuation of age field is checked, and if that number is not bigger than 0, the message of error will be  displayed.
finally, we check if the gender is chosen.

If the form has passed all the checkings and no error apears, then the submit action will start.

Download example

Are you a website owner?
Click here to register and submit your tutorials!

Browse by category

Most popular tutorials