PHP Form Validation

While Validating a HTML form the client side validation is not only enough. Since our web application allows outsiders to enter data, server side form validation is also required for additional security.

Here, we are going to see how to validate a form using PHP. We have a registration form containing name, password, email and gender fields. All the fields are mandatory and should not empty. The email should be in correct format. We are going to check these validations in server side.

registration_form

Validating Form PHP in-builts.

PHP provides empty() function to check a variable is empty. We are using this function to check if all the text fields are empty or not. We are using isset() to check the gender radio button is checked or not. We are validating email format by using PHP filter_var() function. The code is,

foreach($_POST as $key=>$value) {
if(empty($_POST[$key])) {
$message = ucwords($key) . " field is required";
break;
}
}
/* Validation to ensure gender is selected */
if(!isset($_POST["gender"])) {
$message = " Gender field is required";
}

/* Validation to ensure about if the checkbox is checked or not */
if(!isset($_POST["terms"])) {
$message = " Check the box to accept Terms and conditions";
}

/* Validation about the right format of user email */
if(!isset($message)) {
if (!filter_var($_POST["userEmail"], FILTER_VALIDATE_EMAIL)) {
$message = "Invalid UserEmail";
}
}

Prepopulate Form with Validation Error Message.

Once the form contains invalid data then this code pre-populates the form with invalid data and display validation errors.


<tr class="tablerow">
<td align="right">User Type</td>
<td>
<select name="userType">
<option value="">--Select--</option>
<option value="Member" <?php if(isset($_POST['userType']) && $_POST['userType']=="Member") { ?>selected<?php  } ?>>Member</option>
<option value="Premium User" <?php if(isset($_POST['userType']) && $_POST['userType']=="Premium User") { ?>selected<?php  } ?>>Premium User</option>
</select>
</td>
</tr>

...

<tr class="tablerow">
<td align="right">Address</td>
<td><textarea rows="3" cols="17" name="userAddress"><?php if(isset($_POST['userAddress'])) echo $_POST['userAddress']; ?></textarea></td>
</tr>

...

<tr class="tablerow">
<td align="right">Gender</td>
<td><input type="radio" name="gender" value="Male" <?php if(isset($_POST['gender']) && $_POST['gender']=="Male") { ?>checked<?php  } ?>> Male
<input type="radio" name="gender" value="Female" <?php if(isset($_POST['gender']) && $_POST['gender']=="Female") { ?>checked<?php  } ?>> Female
</td>
</tr>
<tr class="tablerow">
<td align="right"></td>
<td><input type="checkbox" name="terms"> I accept Terms and Conditions</td>
</tr>

Download

This HTML code tutorial was published on May 23, 2013.

↑ Back to Top