Recent Posts

Topics

Archives


« | Main | »

How to validate a form using JavaScript

By Jesse | September 16, 2008

Alot of companies have forms on their websites to help capture lead information and communicate effectively with customers and partners. Getting incomplete or invalid information can lessen the value of a potential lead so it is important to get complete and accurate information the first time.

To validate a javascript form add a javascript function that contains the validation information… Below is an example.

Add this section to the form html page between the header tags (adjust as necessary for your page):

<script language=”JavaScript” type=”text/javascript”>
<!– // function validate(form)
{
if(form.first.value == “”) {
window.alert(“Please make sure the \’ First Name \’ field was properly completed.”);
return false;
}
if(form.last.value == “”) {
window.alert(“Please make sure the \’ Last Name \’ field was properly completed.”);
return false;
}
if(form.phone.value.length < 12) {
window.alert(“Please make sure the \’ Phone \’ field is formated as: 703-555-5555.”);
return false;
}
}

As you can see we are basically looking at a values entered and then comparing them to what we expect to find.

Now we must add the section of code that triggers our function to run.

In the top of the form add this: onsubmit=”return checkform(this);

so your new line would be :

<form method=”POST” action=”submit.asp” name=”form” onsubmit=”return validate(this);”>

This will now call the javascript function when the user clicks the submit button. It will not launch the submit.asp page until the user has passed the validation test.

To test for not a value put an ! infront of the equation to be tested like the example below:

if(!(form.phone.value.length < 12)) { ……

_______________________________________
PLEASE HELP BY BOOKMARKING OUR SITE...
[del.icio.us] [Digg] [StumbleUpon]

Topics: How To, IT Security, Web Design / SEO | No Comments »

Comments