I wrote this for a php Guest Book app I wrote.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | function validateForm(str)
{
// first name is required
var fn=document.forms[str]["first_name"].value;
if (fn == "")
{
alert("Please Fill In First name");
return false;
}
// last name is required
var fn=document.forms[str]["last_name"].value;
if (fn == "")
{
alert("Please Fill In Last name");
return false;
}
// verify email if provided
var em=document.forms[str]["email"].value;
if (em != "") {
var atpos=em.indexOf("@");
var dotpos=em.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
{
alert("You have entered an invalid e-mail address");
return false;
}
}
}
|
To use this code you will have to include it with <SCRIPT> within the HTML or as a seprate file. The function assumes that you will pass in the name of the form it needs to validate. On the submit button you will have to include:
onclick="javascript:return validateForm('form');
Tags: form, javascript