Easily Generate Javascript and PHP Error Checking For Your Forms

I wanted a quick and easy way of adding Javascript and PHP error checking to my form elements. The benefit of this is that errors can be caught using Javascript before the form is submitted, but if JS is disabled in the users browser then the error is still caught using PHP.

The method I came up with to solve this is very simple and can be easily added to form elements with little extra code. The error checking is done by checking input against regular expressions.

See the demo and demo source code.

Code Explaination

One function is used to create both forms of error checking:

<?php
$jsChecks = ""; //holds JS error checks
$errorFound = false;	//PHP error flag
 
//Creates both JS and PHP error checks
function errorCheck($elementName, $regExp, $errMsg) {
	global $jsChecks;
	global $errorFound;
	//Create Javascript error checking
	$check = '
	var ' . $elementName . 'Filter = ' . $regExp . '; 
	if (!' . $elementName . 'Filter.test(theForm.' . $elementName . '.value)) { 
		errorMessage += "\n  * ' . $errMsg . '";
		errorFound = true;
	}' . "\n";
	$jsChecks .= $check;
 
	//PHP error checking and return input class
	if(isset($_POST["formSubmitted"])) {	//if form submitted
		if(!preg_match($regExp, $_POST[$elementName])) {
			$errorFound = true;
			return "error"; //css error class
		}
	}
	return "";	//no class if no error detected
}

Error checking is created for the form elements specifying which element (by name), a regular expression to be checked against and a custom error message:

//Create error checking
$nameError = errorCheck("name", "/([a-z0-9]{3}[a-z0-9]?)/", "Name is too short");	//Must be 3 chars or over
$emailError = errorCheck("email", "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", "Invalid Email Address");	//must be valid email address

If no error is found then process the data.

//If no error found
if(!$errorFound) {
	//Process form data...
}
?>

In our head tags we add the following Javascript and CSS rules. The Javascipt checks we created for each element are included here by the PHP ehco:

 
<style type="text/css">
input {
	border: 1px solid #DDD;
}
.error {
	border: 1px dashed #F00;
}
</style>
 
<script type="text/javascript">
<!--
function validateForm(theForm) {
	var errorFound = false;
	var errorMessage = "Please correct the following errors:\n";
	<?php echo $jsChecks ?>
	if(errorFound) {
		alert(errorMessage);
	}
	return !errorFound;
}
//-->
</script>

The form is really simple with code to display a CSS class depending on whether a error is detected (for the PHP error checking) and to set the value of the field:

 
<form method="post" onSubmit="return validateForm(this)">
	<label for="name"><strong>Name</strong> (must be 3 characters or over)</label><br />
	<input type="text" name="name" id="name" size="30" class="<?php echo $nameError ?>" value="<?php echo @ $_POST['name'] ?>" /><br />
	<label for="email"><strong>Email Address</strong> (must be a valid email address)</label><br />
	<input type="text" name="email" id="email" size="30" class="<?php echo $emailError ?>" value="<?php echo @ $_POST['email'] ?>" />
	<br />
	<input type="hidden" name="formSubmitted" id="formSubmitted" value="true" />
	<input type="submit" value="Submit" />
</form>

There you are, both Javascript and PHP error checking! See the complete source code here.

Tags: Web Development


You can leave a response, or trackback from your own site.

One Response to “Easily Generate Javascript and PHP Error Checking For Your Forms”

  1. morehawes says:

    A slightly better modification to this script would be to display the error message next to the input field for the PHP error checking.

    This requires a little extra code but provides the user with more information. The demo can be seen here and the source code here.

    This does bloat the HTML input fields even more which could be reduced by using PHP to build parts, or all of the HTML input field outside of the HTML to keep it clean. However I am concerned with the ease of adding these error checks when creating new input fields in favour of extra code.

Leave a Reply