Skip to main content

PHP Form Validation Tutorial, Technique and Library

Validating a form before processing the user input is one of the very important things. Validation of the input data will protect your application from accepting any unwanted input. Validation can be done in various stages of validation using client side script i.e. javascript. Restricting the form filed to take unwanted input using javascript. But Javascript can be easily disabled or the user can use curl to directly hit data on your form. So server side validation is very very important when you are creating any form. So here we will learn different kinds of PHP form validation technique. Also, in last, we will learn to write a php form validation class library.

Before proceeding further you may get a complete idea of creating a form by reading my post PHP Form Handling.

Also, this tutorial is for those who want to understand the form validation. In the later part of the tutorial, we will create a form validation class which you can use. But yes, primarily this tutorial if more for the beginners who wants to understand the technique of PHP form validation rather than just a simple class.

What is PHP Form Validation?

PHP Form validation is a way to validate the user input of a web application form on the server side when a user submits the form and prompt user for all invalid input.

For Example, You have created a user registration form with following input:

  1. Username: A textbox field
  2. Password: A password field
  3. First Name: A textbox field
  4. Last Name: A textbox field
  5. Email Address: A textbox field
  6. Gender: A radio button field
  7. Mobile Number: A textbox field.
  8. Country: A dropdown.

Now the question is, why you have taken above fields, definitely, there would be some purpose, for example, for the field username and password purpose is to provide login feature. The purpose of email address and the mobile number would be for communication with the user via email or SMS. Now just think about the login feature, if a user has not fielded username or more than 1 user has entered the same username. Your login will not work. Similarly, think about email address and mobile number.

Below are the validation rules which you might think on above registration form.

  1. Username: Must not be empty and has to be unique. If the username is already taken by another person just notify the user.
  2. Password: Must not be empty. For a strong password, you can also put validation of minimum 8 characters and the password must contain at least 1 capital later, one small letter and at least one numeric.
  3. First Name: Must not be empty.
  4. Last Name: No validation.
  5. Email Address: Must not be empty and has to be a valid email format.
  6. Gender: At least one button is checked.
  7. Mobile Number: Must not be empty and 10 digit number.
  8. Country: At least one country from the country dropdown is selected.

Form Validation Type

Generically we can classify the form validation type in the following category:

  1. Required Field Validation: To validate for the user has not entered any value.
  2. Data type validation: To validate the data type whether the input has to be integer or string.
  3. Data Format Validation: To validate the format like email format, credit card format etc.
  4. Custom Validation: Validate the user input on the basis of any custom rule. For example new username with lists of existing, usernames.
  5. Data Limit Validation: Validation of the number of character like 10 digits for mobile number, 150 characters for biography etc.

I will demonstrate some examples of every type of validation with PHP example code.

PHP Form Validation Basic Technique and Logic

You should always validate the form one you received the form. Your form will be received at the server with user submitted data by either of GET or POST method. If the from has sensitive information use POST method instead of GET. In next sections, I will demonstrate all example with POST methods.

You can check for user submitted form by using below code using $_SERVER Variable in PHP:

if($_SERVER['REQUEST_METHOD'] == 'POST'){
//Write your validation Logic.
//Check for success of validation
//If success write code to process your data.
}

Within the If statement written in above code, you may write your validation logic to validate user-submitted input. Once the validation is successful you can process the data further and show the success message to your user. In case the data is not validated just show the form with what user has entered on the same form. If you will post the form on other page using code like from www.yoursite.com/register.php to www.yoursite.com/save.php then in case of validation faild you have to either

If you will post the form on other page using code like from www.yoursite.com/register.php to www.yoursite.com/save.php then in case of validation failed you have to either take your user back to the register.php page with form data posted on save.php or put your form code in separate file which needs to be included on both register.php and on save.php(on save.php only if validation failed). So to mitigate these process complexity I prefer to post the form on the same page and on the basis of $_SERVER[‘REQUEST_METHOD’] validate and process the form data. Although it makes your code little complex but flow become easy.
PHP Form Validation Process

Basic Example Code of PHP Form Validation

Let us take an example of a very small registration form which has some basic field like username, password, name, telephone.

Below is the HTML Code:
<html>
<head>
<title>Basic Form Validation</title>
</head>
<body>
<h1>Basic Registration</h1>
<form method="post" action="basic-form-validation.php">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br>
<label for="password">Password</label>
<input type="password" id="password" name="password"/><br>
<label for="name">Name</label>
<input type="text" id="name" name="name"/><br>
<label for="Phone">Phone</label>
<input type="text" id="Phone" name="Phone"/><br>
<input type="submit" value="Register"/>
</form>
</body>
</html>

And it will create below form:
Basic Form for ValidationNow let us write validation Code. Below is the PHP form validation code:

<?php
$has_error = false; //A variable wich will be set to true if there is any error;
$error_message = array('username'=>'' , 'password'=>'' , 'phone'=>''); //An array which will have validation message with key as form name
if ($_SERVER['REQUEST_METHOD'] == 'POST') {//Check if the form is posted
if (empty($_POST['username'])) {//If username is empty just
$has_error = true;
$error_message['username'] = 'Username must not be blank';
} else {
if (strlen($_POST['username']) < 5) {
$has_error = true;
$error_message['username'] = 'Username has to be atleast 5 charecter long';
}
}
if(empty($_POST['password'])){
$has_error = true;
$error_message['password'] = 'Password must not be blank';
}
if(!empty($_POST['phone']) && !is_numeric($_POST['phone'])){
$has_error = true;
$error_message['phone'] = 'A phone number must be numeric and only x';
}
//If has_error is still false it means that no any validation failed. Just write form processing logic
if(false == $has_error){
/* Write Code to insert the user detail in DB */
echo 'Registration Done. Thanks';die;
}
}
?>
<html>
<head>
<title>Basic Form Validation</title>
</head>
<body>
<h1>Basic Registration</h1>
<form method="post" action="basic-form-validation.php">
<label for="username">Username</label>
<input type="text" id="username" name="username" value="<?php echo isset($_POST['username']) ? $_POST['username']: '' ?>" />
<?php echo $error_message['username'] ?>
<br>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
<?php echo $error_message['password'] ?>
<br>
<label for="name">Name</label>
<input type="text" id="name" name="name" value="<?php echo isset($_POST['name']) ? $_POST['name']: '' ?>" /><br>
<label for="phone">Phone</label>
<input type="text" id="phone" name="phone" value="<?php echo isset($_POST['phone']) ? $_POST['phone']: '' ?>" />
<?php echo $error_message['phone'] ?>
<br>
<input type="submit" value="Register"/>
</form>
</body>
</html>

Now let us evaluate the code script block in one by one step.

Evaluation of PHP Form Validation Code Example

First thing we did is declared following 2 variable in our php code block:

$has_error = false; //A variable wich will be set to true if there is any error;
$error_message = array('username'=>'' , 'password'=>'' , 'phone'=>''); //An array which will have validation message with key as form name

$has error is simply a flag which will be true in case of any error. The variable $error_message is an array which every index is related with the error message for every the input types.

Now as a next step we are just validating every input type as per our requirement by checking the post request method. And finally if there is no any error simply doing the data processing and stopning the execution with the help of below code.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {//Check if the form is posted
if (empty($_POST['username'])) {//If username is empty just
$has_error = true;
$error_message['username'] = 'Username must not be blank';
} else {
if (strlen($_POST['username']) < 5) {
$has_error = true;
$error_message['username'] = 'Username has to be atleast 5 charecter long';
}
}
if(empty($_POST['password'])){
$has_error = true;
$error_message['password'] = 'Password must not be blank';
}
if(!empty($_POST['phone']) && !is_numeric($_POST['phone'])){
$has_error = true;
$error_message['phone'] = 'A phone number must be numeric and only x';
}
//If has_error is still false it means that no any validation failed. Just write form processing logic
if(false == $has_error){
/* Write Code to insert the user detail in DB */
echo 'Registration Done. Thanks';die;
}
}

 

So in the above code we are doing the complete validation and processing. Some of the validation is like below:

if (empty($_POST['username'])) {//If username is empty just
$has_error = true;
$error_message['username'] = 'Username must not be blank';
} else {
if (strlen($_POST['username']) < 5) {
$has_error = true;
$error_message['username'] = 'Username has to be atleast 5 charecter long';
}
}

Now if the validation will fail again the form will be shown with the message from $error_message variable and in input type we are echoing the value previously fielded by the user.

<label for="username">Username</label>
<input type="text" id="username" name="username" value="<?php echo isset($_POST['username']) ? $_POST['username']: '' ?>" />
<?php echo $error_message['username'] ?>

This code is still vulnerable and you should not use for your live website. The code written here is only for learning purpose.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

2 thoughts on “PHP Form Validation Tutorial, Technique and Library

  1. Informative blog.. This blog having more useful information about form validation and having clear explanation so easy to understand.. thank you for sharing

shares