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:

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.

1 Comment

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked