Easily Generate Javascript and PHP Error Checking For Your Forms
Posted on 10/04/2009 under Web Development
Code Explaination
One function is used to create both forms of error checking:
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:
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:
There you are, both Javascript and PHP error checking! See the complete source code here.