PHP Form Validation with example

PHP Form Validation is the backend or server-side validation. It prevents from entering invalid data into the input field. So, You must integrate it into your project form.

In this tutorial, I have created a general validation script with a registration form. But you need not worry, you can implement this script with other different types of form.

 

PHP Form Validation

How to Validate Form Using PHP

Before validating the form, You have to set the following basic requirements.

Create Form Validation Rules that are required in your project form

  • All the Input Fields must be required.
  • First Name & Second name must accept only characters with a single white space
  • Email Address must be valid format containing @ symbol.
  • The password must contain a combination of one uppercase & lowercase letter, number, special characters & minimum characters length 8. Even It will not accept any white spaces.
  • Confirm password must be matched with a password.

If the users do not enter valid data according to the above validation rule, they will not be able to submit the form data to the server.

Read Also 

jQuery form  Validation

Create Registration Form Using PHP

You should also create the following folder structure

validation-form/
    |__validation-script.php
    |__validation-form.php
    |

1. Create a Validation Form Using HTML

You have to configure the following steps to create a validation –

  •  First, Include validation-script.php
  • Also, include the following bootstrap4 libraries to customize the form
  • Write HTML code to create a form.

File Name – validation-form.php

<?php

include('validation-script.php');
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <title>PHP Form Validation</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!--bootstrap4 library linked-->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

  <!--custom style-->
  <style type="text/css">
   .registration-form{
      background: #f7f7f7;
      padding: 20px;
      border: 1px solid orange;
      margin: 50px 0px;
    }
    .err-msg{
      color:red;
    }
    .registration-form form{
      border: 1px solid #e8e8e8;
      padding: 10px;
      background: #f3f3f3;
    }
  </style>
</head>
<body>

<div class="container-fluid">
 <div class="row">
   <div class="col-sm-4">
   </div>
   <div class="col-sm-4">
    
    <!--====registration form====-->
    <div class="registration-form">
      <h4 class="text-center">Create a New Account</h4>
      
<p class="text-success text-center"><?php echo $valid; ?></p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">


        <!--//first name//-->
        <div class="form-group">
           <label for="email">First Name</label>
               
<input type="text" class="form-control" placeholder="Enter First Name" name="first_name" value="<?php echo $set_firstName;?>">

           <p class="err-msg">
    
<?php if($fnameErr!=1){ echo $fnameErr; }?>

           </p>
        </div>

        <!--//Last name//-->
        <div class="form-group">
            <label for="email">Last Name</label>
                
<input type="text" class="form-control" placeholder="Enter Last Name" name="last_name" value="<?php echo $set_lastName;?>">

            <p class="err-msg"> 
    
<?php if($lnameErr!=1){ echo $lnameErr; } ?>

            </p>
        </div>
        
        <!--// Email//-->
        <div class="form-group">
            <label for="email">Email:</label>
                
<input type="text" class="form-control" id="email" placeholder="Enter email" name="email" value="<?php echo $set_email;?>">

            <p class="err-msg">
    
<?php if($emailErr!=1){ echo $emailErr; } ?>

            </p>
        </div>
        
        <!--//Password//-->
        <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="password" class="form-control"  placeholder="Enter password" name="password">
            <p class="err-msg">
                
<?php if($passErr!=1){ echo $passErr; } ?>

            </p>
        </div>

        <!--//Confirm Password//-->
        <div class="form-group">
            <label for="pwd">Confirm Password:</label>
            
                
            <input type="password" class="form-control" placeholder="Enter Confirm password" name="cpassword">
            <p class="err-msg">
                
<?php if($cpassErr!=1){ echo $cpassErr; } ?>

            </p>
        </div>
    
        <button type="submit" class="btn btn-danger" value="Register" name="register">Register Now</button>
      </form>
    </div>
   </div>
   <div class="col-sm-4">
   </div>
 </div>
  
</div>

</body>
</html>

 

2. Validate Form Using PHP

extract($_POST) – By defined it. We need not access the value of the field using $_POST, you can only access the values of the fields by declaring variables with their name like

Field Name $_POST[‘field_name’] extract($_POST)
first_name $_POST[‘first_name’] $first_name
last_name $_POST[‘last_name’] $last_name
email $_POST[’email’] $email
password $_POST[‘password’] $password
cpassword $_POST[‘cpassword’] $cpassword

Validation with Regular Expression –

Variables Regular Expression Validation
$validName /^[a-zA-Z ]*$/ Digits are not allowed
$validEmail /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ Valid email format with @ symbol
$uppercasePassword /(?=.*?[A-Z])/ at least one uppercse only
$lowercasePassword /(?=.*?[a-z])/ at least one lowercase only
$digitPassword /(?=.*?[0-9])/ at least one digit only
$spacesPassword /^$|\s+/ for spaces only
$symbolPassword /(?=.*?[#?!@$%^&*-])/   for at least one special characters only
$minEightPassword /.{8,}/ for at least 8 characters length

 

Input Validation Rule

  • First Name Input Field accepts only characters with a single white space
  • Second Name input Filed accepts only characters with a single white space
  • Email Input Field accepts only valid email format string with @ symbol
  • Password Input accepts a combination of one uppercase & lowercase letter, number, special characters & minimum characters length 8. Even It will not accept any white spaces.
  • Value of Confirmed password Input Field must be matched with the values of password input Field

Condition for all the fields are valid or not – When all the validations return true( true=1) then if block of the statement will execute otherwise else block of statement

legal_input() function: If anyone enters illegal data into the fields then legal_input() will convert into legal data.

trim() – If the user enters the data with both side spaces, then it will remove those spaces from both sides.

stripslashes() – If the user enters the data with backslashes (\), then it will remove backslashes (\).

htmlspecialchars() – If the user enters the data like the following formate

<script>location.href('http://www.unkownsite.com')</script>

then it will be converted into HTML escaped code like the following formate

&lt;script&gt;location.href('http://www.unkownsite.com')&lt;/script&gt;

According to the above point, I have written a validation script that can protect the form from illegal input values. This code works in all kinds of forms like contact, registration & login form.

File Name – validation-script.php

 <?php

// by default, error messages are empty
$valid=$fnameErr=$lnameErr=$emailErr=$passErr=$cpassErr='';

// by default,set input values are empty
$set_firstName=$set_lastName=$set_email='';    
 extract($_POST);

if(isset($_POST['register']))
{
   
   //input fields are Validated with regular expression
   $validName="/^[a-zA-Z ]*$/";
   $validEmail="/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/";
   $uppercasePassword = "/(?=.*?[A-Z])/";
   $lowercasePassword = "/(?=.*?[a-z])/";
   $digitPassword = "/(?=.*?[0-9])/";
   $spacesPassword = "/^$|\s+/";
   $symbolPassword = "/(?=.*?[#?!@$%^&*-])/";
   $minEightPassword = "/.{8,}/";

 //  First Name Validation
if(empty($first_name)){
   $fnameErr="First Name is Required"; 
}
else if (!preg_match($validName,$first_name)) {
   $fnameErr="Digits are not allowed";
}else{
   $fnameErr=true;
}

//  Last Name Validation
if(empty($last_name)){
   $lnameErr="Last Name is Required"; 
}
else if (!preg_match($validName,$last_name)) {
   $lnameErr="Digits are not allowed";
}
else{
   $lnameErr=true;
}

//Email Address Validation
if(empty($email)){
  $emailErr="Email is Required"; 
}
else if (!preg_match($validEmail,$email)) {
  $emailErr="Invalid Email Address";
}
else{
  $emailErr=true;
}
    
// password validation 
if(empty($password)){
  $passErr="Password is Required"; 
} 
elseif (!preg_match($uppercasePassword,$password) || !preg_match($lowercasePassword,$password) || !preg_match($digitPassword,$password) || !preg_match($symbolPassword,$password) || !preg_match($minEightPassword,$password) || preg_match($spacesPassword,$password)) {
  $passErr="Password must be at least one uppercase letter, lowercase letter, digit, a special character with no spaces and minimum 8 length";
}
else{
   $passErr=true;
}

// form validation for confirm password
if($cpassword!=$password){
   $cpassErr="Confirm Password doest Matched";
}
else{
   $cpassErr=true;
}

// check all fields are valid or not
if($fnameErr==1 && $lnameErr==1 && $emailErr==1 && $passErr==1 && $cpassErr==1)
{
   $valid="All fields are validated successfully";


   
   //legal input values
   $firstName= legal_input($first_name);
   $lastName=  legal_input($first_name);
   $email=     legal_input($email);
   $password=  legal_input($password);

   // here you can write Sql Query to insert user data into database table
}else{
     // set input values is empty until input field is invalid
    $set_firstName=$first_name;
    $set_lastName= $last_name;
    $set_email=    $email;
}

}


// convert illegal input value to ligal value formate
function legal_input($value) {
  $value = trim($value);
  $value = stripslashes($value);
  $value = htmlspecialchars($value);
  return $value;
}
?>

 

My Suggestion

Dear Developers, I hope you have learned PHP Form Validation. Now you can easily validate the form of your project. If you have any doubts or questions related to this tutorial, you can ask me through the below comment box. I will reply as soon as possible.

Thanks For giving me time for this tutorial…

 

Categories PHP

7 thoughts on “PHP Form Validation with example”

  1. Crazy question – now that the data has been validated how do you call a process.php form to insert the data into a database?

    Reply
  2. Hello thank you for this tutorial,
    I have a question regarding the legal name() function, as I searched in the internet I never seen it used or mentioned, plus can you explain its role in this particular script thank you.

    Reply

Leave a Comment