JavaScript – Quick Validation

I will be the first to admit that I am not a Javascript king so this may be so elementary to most.

This is a very easy way to verify that fields are filled in and the email address is a proper format.  Make sure that your form has a proper name and that all your text entry fields also have proper names.  Let’s say I have the following:

<form name=”test” action=”submit.php” method=”post”>
First Name: <input type=”text” name=”first_name”>
Last Name: <input type=”text” name=”last_name”>
Email Address: <input type=”text” name=”email_address”>
<input type=”submit” value=”submit”>

All you will need to add to your form is a “onsubmit” to the form tag, like this

<form name=”test” action=”submit.php” onsubmit=”return good_text();”method=”post”>

Once this is done all you will have to do is add the goodtest() javascript function.  I put the function at the top of the html.  I don’t know if this is correct but it is where I am used to putting a lot of functions.  So right below your body tag enter the following

function good_text()
var first_n=document.forms[“notify”][“first_name”].value
var last_n=document.forms[“notify”][“last_name”].value
var email_a=document.forms[“notify”][“email_address”].value
var email_at=email_a.indexOf(“@”);
var email_dot=email_a.lastIndexOf(“.”);

if (first_n==null || first_n==””)
alert(“The First Name Field is Empty, this must be filled out.”);
return false;

if (last_n==null || last_n==””)
alert(“The Last Name Field is Empty, this must be filled out.”);
return false;

if (email_at<1 || email_dot<email_at+2 || email_dot+2>=email_a.length)
alert(“This is Not a Valid Email Address”);
return false;

Really all this java script is doing is looking to see if there is a value for the first_name.  If there isn’t it alerts the user.  If there is it looks to see if there is a value for the last_name.  If there isn’t then it alerts the user.  Once these to fields have values entered into them the script will check for a generic email pattern.  If it does not find this pattern it will alert the user.

The really nice thing here is that the form will not get submitted untill all fields are filled in and the email address looks like an email address.  Just remember this only checks for data it DOES NOT check the data it’s self.  This will not protect against SQL injection or Cross Site Scripting!

Leave a Reply

All Work on this site is not to be reproduced without written permision from Nick Schroedl.