Validating a form using a PHP filter and a regular expression

Originally written by James Richardson on 01/11/2009

Validating your form with php filters and javascript regular expressions

Validating your user input is imperative, especially when using databases. If a user inputs bad information into your database, bad things can happen. To make a long story short, users need to input the correct information, and be told when they inputted something incorrect. This tutorial will explain how to use two different methods of validating a form, the Regular expression match and the PHP filter. This tutorial is design to explain these methods as simply as possible. The purpose is to show how two different ways can be used in one tutorial. It is kind of "Killing two birds with one stone." So lets get started on the validation process.

Create the Form

All of the following code will be placed into the body section of the php document. The first thing you need to create is a form. (See code below) This form is very simple and only has two text fields, a reset and a submit button, and a hidden input. In the form, the action will be set to <?php $_SERVER['PHP_SELF']; ?>. The action is set to this so that when the form is submitted, the information will be directed to the same page on the server. The method is set to "POST" so the information is not seen in the URL.

The inputs need to be named appropriately, The "name" of the input is variable that the form sends. This is important to get correct or the variables will not be recognized in the code. The hidden input is so that when the form is sent, the variable submitted is sent as well.

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
  <p>Name: <input name="name" type="text" /></p>
  <p>Email: <input name="email" type="text" /></p>
  <input name="submit" type="submit" value="Validate" />
  <input name="reset" type="reset" value="Reset" />
  <input name="submitted" type="hidden" value="submitted" />
</form>

Checking if the form is submitted

The "submitted" variable will be sent through the post method and checked in a conditional statement to check whether or not the form has been submitted. (See code below) The PHP isset() function checks to se if the variable "submitted" has been sent through the post method. If the variable is sent, then the validation code will be executed.

<?php
if (isset($_POST['submitted'])){
  //Validation Code goes here
}
?>

Regular Expression Validation

Next we will put in the code that will be used to validate a name using a regular expression. You can validate many different things with regular expressions; but, here we will keep it simple and only validate a name. (See code below) First, we need to check if the variable was sent from the form with the empty() function.

If the variable is empty , "No name was entered" will display. ElseIf the variable is not !empty(), the "$name" variable will be matched to the "$pattern" variable with the preg_match() function. "$pattern" variable is equal to the regular expression. Regular expressions can be made to match virtually any pattern from email addresses to url's.

To see a good list of regular expressions visit Roscripts. If the user input matches the pattern "user input is a valid name" will display. Otherwise, "user input is not a valid".

// Validation with PHP regular expression
if (empty($_POST['name'])){
  echo 'No name was entered!<br />';
}elseif (!empty($_POST['name'])){
  $name = $_POST['name']; //
  $pattern = '/^[a-zA-Z]{1,25}$/';		
  if (preg_match($pattern,$name)){ 
    echo '<b>'.$name.'</b> is a valid name.<br />';
  }else{ 
    echo '<b>'.$name.'</b> is not a valid name.<br />';
  }
}

PHP Filter Validation

Next we will put in the code that will be used to validate a email using a PHP Filter. This is done basically the same as the Regular expression validation. You can validate many different things with php filters; but, here we will keep it simple and only validate a email. (See code below) First, we need to check if the email variable was sent from the form with the empty() function. If the variable is empty , "No email was entered" will display. ElseIf the variable is not !empty(), the "$email" variable will be matched to the filter_input() function.

In this case we are checking if it is not "!" the match to the filter. The filter_input() function takes 3 parameters: INPUT_POST, "email", and FILTER_VALIDATE_EMAIL. The INPUT_POST parameter is retrieving the variable using the POST method. You can use the GET method as well. The "email" parameter is the variable that was sent from the form.

The FILTER_VALIDATE_EMAIL parameter is the email filter that the email address will be compared to. FILTER_VALIDATE_EMAIL is built in to PHP and has all of the email parameters in it. If the email does not match the FILTER_VALIDATE_EMAIL filter, the message "your email is not a valid email address" will display. Else, "your email is a valid email address" will display. The variable "$email" is for displaying what the user inputted.

// Validation with PHP Filter
if (empty($_POST['email'])){
  echo 'No email was entered!<br />';
}elseif (!empty($_POST['email'])){
  $email=$_POST['email'];
  if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)){
    echo '<b>'.$email.'</b> is not a valid Email address.';
  }else{
    echo '<b>'.$email.'</b> is a valid Email address';
  }
}

Validation in the Submittal

Once you have you validation code created, you can place them into the Conditional statement you created for when the form is submitted. (See code below) When the form is submitted, the code will execute, checking the form inputs to the conditions in the code. Whatever the outcome, the appropriate message will display.

<?php
if (isset($_POST['submitted'])){
  // Validation with PHP regular expression
  if (empty($_POST['name'])){
    echo 'No name was entered!<br />';
  }elseif (!empty($_POST['name'])){
    $name = $_POST['name'];
    $pattern = '/^[a-zA-Z]{1,25}$/';		
    if (preg_match($pattern,$name)){ 
      echo '<b>'.$name.'</b> is a valid name.<br />';
    }else{ 
      echo '<b>'.$name.'</b> is not a valid name.<br />';
    }
}
	
  // Validation with PHP Filter
  if (empty($_POST['email'])){
    echo 'No email was entered!<br />';
  }elseif (!empty($_POST['email'])){
    $email=$_POST['email'];
    if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)){
      echo '<b>'.$email.'</b> is not a valid Email address.';
    }else{
      echo '<b>'.$email.'</b> is a valid Email address';
    }
  }
}
?>

The whole code

Below is all of the code inside the appropriate HTML. You can copy and past this whole section into a PHP file and it will work for you. This concludes the PHP filter and Regular expression validation tutorial. For more information on PHP filters you can go to w3schools PHP filter references.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP Form Validation</title>
</head>

<body>
<h2>PHP Form Validation</h2>
<?php
if (isset($_POST['submitted'])){
  // Validation with PHP regular expression
  if (empty($_POST['name'])){
    echo 'No name was entered!<br />';
  }elseif (!empty($_POST['name'])){
    $name = $_POST['name'];
    $pattern = '/^[a-zA-Z]{1,25}$/';		
    if (preg_match($pattern,$name)){ 
      echo '<b>'.$name.'</b> is a valid name.<br />';
    }else{ 
      echo '<b>'.$name.'</b> is not a valid name.<br />';
    }
  }

  // Validation with PHP Filter
  if (empty($_POST['email'])){
    echo 'No email was entered!<br />';
  }elseif (!empty($_POST['email'])){
    $email=$_POST['email'];
    if (!filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)){
      echo '<b>'.$email.'</b> is not a valid Email address.';
  }else{
    echo '<b>'.$email.'</b> is a valid Email address';
  }
}
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
  <p>Name: <input name="name" type="text" /></p>
  <p>Email: <input name="email" type="text" /></p>
  <input name="submit" type="submit" value="Validate" />
  <input name="reset" type="reset" value="Reset" />
  <input name="submitted" type="hidden" value="submitted" />
</form>
<p><a href="validate.php">Clear Errors</a></p>
</body>
</html>

Get a copy of My Banjo Buddy!


Recent articles



Top


100% Browser Compliant
         
100% Valid HTML5