Advanced PHP Form Validation
Last year I wrote an article in how to implement basic validation for a form with PHP. I decided to re-look at this and improve what I did in that article. This time we are going to make a more advanced PHP form that is more responsive and effective.
This PHP sample code has many advantages over the previous article. Not only that, but for the most part it is easier to implement with more complexed forms where you need more than basic validation.
Below are the requirements for the code included in this PHP form tutorial:
You can view a demo of the PHP form in action. You will not only see the standard validation (email, phone, and required fields), but we also take it a step further by validating check boxes. If the visitor checks the newsletter option, they must then check two topics before the form can be submitted (in the same way, you can do something like this with radio buttons). If there are errors in the form, and those errors are corrected, they will immediately disappear.
I took an example from the jQuery validation documentation and tweaked it a little bit to fit the form, for this PHP tutorial.
Form HTML Page
Below is the html for the page where the form will sit.
One thing you will notice is that there is no PHP code on this page. You will also notice that jQuery is used heavily. In the head tag we define which fields are required and the error messages to display if the field is not entered correctly. This is the largest improvement over the last form example, since the client side error handling is immediate and it displays the errors without posting the form. There was no client side validation in the previous PHP form article.
If you are not familiar in working with jQuery, I highly recommend going through some basic jQuery examples. The bundled code I provide at the end of this PHP tutorial includes the jQuery files necessary in making this example work.
PHP: Process the Form
A configuration area was added to the beginning of the file. Notice that in this code, if there is are no errors processing the form, we display the errors on this page instead of the previous form. This does several things:
2. This simplifies things. We don’t have to use PHP on the form html page at all.
I also do not use the short tag version of calling PHP for compatibility.
Did you like this article?
Please help us spread the word about this site by tweeting, digging and sharing this article around the web (see the buttons immediately above).
38 Comments or Pings to Advanced PHP Form Validation
Trackbacks & Pings