PHP Form validation


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.

PHP Form validation process


Base HTML file

<html lang="en">
<meta charset=utf-8>
<title>Form validation with parsely.js</title>
<link href="../../twitter-bootstrap/twitter-bootstrap-v2/docs/assets/css/bootstrap.css" rel="stylesheet">
<link href="parsely.css" rel="stylesheet">
<style type="text/css">
h1 {margin-bottom:20px}
input, label {margin-top:7px; margin-bottom:7px; color:#000066; font-size: 18px; padding-right: 7px}
input[type='checkbox'] {margin-left: 5px}
.note {color: #ff0000}
<div class="container">
<h1>Travel reservation form</h1>
<h3><span class="note">*</span> denotes mandotory</h3>
<form id="registration_form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">


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

<label>Full name<span class="note">*</span>:</label>
  <input type="text" name="full_name" placeholder="FirstName LastName" autofocus="autofocus" value="<?php echo $_POST['full_name']; ?>">   
  <?php echo "<p class='note'>".$msg_name."</p>";?>
  <?php echo "<p class='note'>".$msg2_name."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//checking name
$msg_name = "You must supply your name";
$name_subject = $_POST['full_name'];
$name_pattern = '/^[a-zA-Z ]*$/';
preg_match($name_pattern, $name_subject, $name_matches);
$msg2_name = "Only alphabets and white space allowed";

email Validation

Code added within the form

<label>Email address<span class="note">*</span>:</label>
  <input type="text" name="email_addr" value="<?php echo $_POST['email_addr']; ?>">
   <?php echo "<p class='note'>".$msg_email."</p>";?>
  <?php echo "<p class='note'>".$msg2_email."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//check email
$msg_email = "You must supply your email";
$email_subject = $_POST['email_addr'];
$email_pattern = '/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/';
preg_match($email_pattern, $email_subject, $email_matches);
$msg2_email = "Must be of valid email format";

Selection list Validation

Code added within the form

<label>Select Tour Package<span class="note">*</span>:</label>	
   <select name="package">
	<option value="Goa" <?= ($_POST['package'] == "1")? "selected":"";?>>Goa</options>
	<option value="Kashmir" <?= ($_POST['package'] == "2")? "selected":"";?>>Kashmir</options>
	<option value="Rajasthan" <?= ($_POST['package'] == "3")? "selected":"";?>>Rajasthan</options>

Code for validation

if (isset($_POST['submit'])) {
$msg_package = "You must select a package";

Date Validation

Code added within the form

<label>Arrival date<span class="note">*</span>:</label>
  <input type="text" name="arv_dt" value="<?php echo $_POST['arv_dt']; ?>">
  <?php echo "<p class='note'>".$msg_dt."</p>";?>
  <?php echo "<p class='note'>".$msg2_dt."</p>";?>
  <?php echo "<p class='note'>".$msg3_dt."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//date validation
$msg_dt = "You must supply an arival date";
    $dt = $_POST['arv_dt'];
    $array = explode("/",$dt);

    $day = $array[1];
    $month = $array[0];
    $year = $array[2];

    if(!checkdate($month, $day, $year))
    $msg2_dt = "Must be in m/d/y format";
    $today = strtotime("now");
    $msg3_dt = "Date supplied is before present day";

Validation for non-empty and non-negative integer

Code added within the form

<label>Number of persons<span class="note">*</span>:</label>
  <input type="text" name="persons" value="<?php echo $_POST['persons']; ?>"s>
  <?php echo "<p class='note'>".$msg_persons."</p>";?>
  <?php echo "<p class='note'>".$msg2_persons."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//checking for non-empty and non-negative integer
$msg_persons = "You must supply number of persons travelling";
$persons = $_POST['persons'];
preg_match("@^([1-9][0-9]*)[email protected]", $persons, $persons_match);
$msg2_persons = "Must be non negative integer";

Checkbox Validation

Code added within the form

<label>What would you want to avail?<span class="note">*</span></label>  
 Boarding<input type="checkbox" name="facilities[]" value="boarding" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][0])) echo "checked" ?> >
 Fooding<input type="checkbox" name="facilities[]" value="fooding" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][1])) echo "checked" ?> >
 Sight seeing<input type="checkbox" name="facilities[]" value="sightseeing" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][2])) echo "checked" ?> >
 <?php echo "<p class='note'>".$msg_facilities."</p>";?>
 <?php echo "<p class='note'>".$msg2_facilities."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//checking facilities
$facilities = $_POST['facilities'];
    $msg_facilities = "You must select facilities";
 if(!empty($_POST['facilities'])) {
    $no_checked = count($_POST['facilities']);
    $msg2_facilities = "Select at least two options";

Validaiton for alphnumeric characters only with a minimum number of characters

Code added within the form

<label>Discout Coupon code:</label>
  <input type="text" name="dis_code" value="<?php echo $_POST['dis_code']; ?>">
  <?php echo "<p class='note'>".$msg_dis."</p>";?>
  <?php echo "<p class='note'>".$msg2_dis."</p>";?>

Code for validation

if (isset($_POST['submit'])) {
//check discount coupon
 $dis_code = $_POST['dis_code'];
 preg_match("/^[a-zA-Z0-9]+$/", $dis_code, $dis_match);
 $msg_dis = "Must be alphanumric"; 
 $msg2_dis = "Must be 10 characters long";

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

<label>Terms and conditions<span class="note">*</span></label>
  <input type="radio" name="tnc" value="agree" <?php echo $tncv; ?>>I agree<br>
  <input type="radio" name="tnc" value="disagree" <?php echo $tnc1v; ?>>I disagree<br>
  <?php echo "<p class='note'>".$msg_agree."</p>";?>
  <?php echo "<p class='note'>".$msg2_agree."</p>";?>
//checking terms 
$tnc = $_POST['tnc'];
case "agree":

case "disagree":
$msg2_agree = "You must agree";

default: // By default 1st option is selected

Submit button

Code added within the form

<button type="submit" class="btn btn-large btn-primary" name="submit">Complete reservation</button>

Final piece of code to let the user know that form is validated

// validation complete 
if($msg_name=="" && $msg2_name=="" && $msg_email=="" && $msg2_email=="" && $msg_package=="" && $msg_dt=="" && $msg2_dt==""&& $msg3_dt=="" && $msg_persons=="" && $msg2_persons=="" && $msg_facilities=="" && $msg2_facilities=="" && $msg_dis=="" && $msg2_dis=="" && $msg_agree=="" && $msg2_agree=="")
$msg_success = "You filled this form up correctly";

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.

echo "



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.

// validation complete 
if($msg_name=="" && $msg2_name=="" && $msg_email=="" && $msg2_email=="" && $msg_package=="" && $msg_dt=="" && $msg2_dt==""&& $msg3_dt=="" && $msg_persons=="" && $msg2_persons=="" && $msg_facilities=="" && $msg2_facilities=="" && $msg_dis=="" && $msg2_dis=="" && $msg_agree=="" && $msg2_agree=="")
$msg_success = "You filled this form up correctly";
//send mail 
$to = "[email protected]";
$subject = "Data collected thorugh from";
$message = "<p>".$_POST["full_name"]."</p><p>".$_POST["email_addr"]."</p><p>".$_POST['package']."</p><p>".$_POST["arv_dt"]."</p><p>".$_POST["persons"]."</p><p>".$_POST["facilities"][0]."</p><p>".$_POST["facilities"][1]."</p><p>".$_POST["facilities"][2]."</p><p>".$_POST["dis_code"]."</p><p>".$_POST['tnc']."</p>";
$from = "[email protected]";

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

PHP: Tips of the Day

PHP: How to convert string to boolean?

Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):

  1. "" (an empty string);
  2. "0" (0 as a string)

If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.

$test_mode_mail = $string === 'true'? true: false;

EDIT: the above code is intended for clarity of understanding. In actual use the following code may be more appropriate:

$test_mode_mail = ($string === 'true');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on".

Ref : https://bit.ly/33SQ3eP