PHP form to email tutorial – Part 3 – Javascript validation

Here in Part 3 we will add Javascript to verify that a Contact Name was filled in before the form goes over to PHP to be processed. This is called client-side validation, since the checks are taking place within the same web page as the form.

Again, it’s just a quick check, so we’re not going to get too fancy with Javascript. If you want to learn serious detail about Javascript, go thru the tutorials at TiZag.

Let’s get started – Open up your html editor and then open up your php form page. You should have this code:
<html>
<head></head>
<form name="adReg" method="POST" action="adaction2.php">
Contact Name:
<br />
<input type="text" name="cName">
<br />
Notes:
<br />
<textarea name="notes"></textarea>
<br />
<input type="submit" name="submit" value="Submit">
</form>
</html>

Add the script tag in the Head area to designate this will be a block of Javascript code:
<html>
<head><script type="text/javascript"></head>


When entering Javascript code, we need to comment it out, so add the starting tag for a comment:
<!--

Define and name the function we want to use to validate the form next. We will name the function and then set it to true initially. That way we can use if statements to check and return a false if the field is empty.
function validate_form ( )
{
valid = true;

Here we go with the if statement, take note of the naming structure for pointing to the field we want to check (validate) on our form.
document.formName.fieldName.value

To check if it contains any entry, we use the double equals sign to ask if that field contains “ANYTHING
if ( document.adReg.cName.value == "" )
{

And if it is empty, we return a false to the script so it does not process and instead we can display a message box to the user with an error message:
alert ( "Please fill in your Name." );
valid = false;
}

Now close out your tags:
}
//-->
</script>

Ok, so we got our Javascript set but how do we tell the Submit button to go check this script before processing it?

We add a line to our Form tag to have the Submit button run our function before “submitting” the form:
<form name="adReg" method="POST" onsubmit="return validate_form ( );" action="adaction2.php">

Sure, there are many ways to expand this validation process in Javascript – adding in an onFocus line to put the cursor back in the missing content field, for example. For this tutorial series, I just wanted to keep to the basics and give you a good foundation for how things are structured, where they go in the overall scheme of code, how the form relates to PHP, and then let you build from there.

For all you ever wanted to know about Javascript check out TiZag’s Javascript tutorials.

The full form page should now have this code:




Contact Name:


Notes:



Want to Leave a Reply?