Powered by Blogger.

May 21, 2011

How to make Form Validation in JavaScript


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



HTML Form
<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;">
</form>
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 = document.myform.email;
var age = document.myform.age;
var gender = document.myform.gender;
if ( nameandsurname.value.indexOf(" ") == -1) {
alert("Enter your Name and Surname.");
nameandsurname.focus();
} else if ((email.value.indexOf("@") == -1) || (email.value.indexOf(".") == -1)) {
alert("Enter your valid email address.");
email.focus();
} else if (! (parseInt(age.value) > 0)) {
alert("Enter your Age.");
age.focus();
} else if (gender.selectedIndex == 0) {
alert("Select your gender.");
gender.focus();
} else {
document.myform.submit();
}
}
</SCRIPT>

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. Enjoy !

 
Examples !



Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Elf Coupons