PHP Form validation
Preface
In this tutorial, we will see how to use PHP to validate the data collected from a form.
You will see how to validate various fields used in general, like text, list, checkbox, radio button and we will also see how to retain POST data, so that after the user submits the form, even if the data supplied is not valid, data is not lost.
Live Demo
Following is a live demo of the PHP form we will create by the end of this tutorial.
Pictorial presentation
The following picture shows what we need to do while validating a form.
Base HTML file
We have used bootstrap for styling the form, but for a few styles we have added some custom styling.
We have used POST
method and action="<?php echo $_SERVER['PHP_SELF']; ?>"
states that after submission form data will be handled by the PHP script present in this file only. You may opt for sending form data to a different file.
Validation for non-empty, alphabets and whitespace only
The following code is added within the form
Code for validation
email Validation
Code added within the form
Code for validation
Selection list Validation
Code added within the form
Code for validation
Date Validation
Code added within the form
Code for validation
Validation for non-empty and non-negative integer
Code added within the form
Code for validation
Checkbox Validation
Code added within the form
Code for validation
Validaiton for alphnumeric characters only with a minimum number of characters
Code added within the form
Code for validation
Note that all the code snippets under "Code for validation" are wrapped by if (isset($_POST['submit']))
and }
. In practice you may keep all of the codes within a single if (isset($_POST['submit']))
and }
.
Validation for radio button
Code added within the form
Submit button
Code added within the form
Final piece of code to let the user know that form is validated
And now you need to disaply a messge informing user that the form is validated. So, we add a single line of PHP code immediately before the form starts.
How to Mail data collected after validation
IF you wish to send data collected through this form after validation to someone's mail address, following code would help you to do so.
So, if you try to understand how to write code for it step by step, step 1 is to declare the mail address to whom you want to send mail, step 2 is to write subject of the mail, step three is to collect data from POST so that you can write them to the body of mail, step 4 is to declare the mail id from which the mail is coming and finally sent mail with PHP mail() function. You may print some message after sending mail optionally.
See also : SQL Injection
Previous: PHP Form handling
Next: PHP Function Reference