• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Home
  • About Us
  • Django
  • Laravel
  • Interview Questions
  • Tips

CodingStatus

- Learn Coding to Build Web Applications

  • JavaScript
  • jQuery
  • ReactJS
  • Ajax
  • Node.js
  • PHP
  • SQL

PHP Form Validation with example

June 5, 2020 By Md Nurullah 19 Comments

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

Contents

  • How to Validate Form Using PHP
    • 1. Create a Validation Form Using HTML
    • 2. Validate Form Using PHP
      • Validation with Regular Expression –
      •  
    • My Suggestion

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 –

VariablesRegular ExpressionValidation
$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…

 

Related Posts:

  • jQuery Form Validation Before Submit
  • Javascript Interview Questions and Answers for Freshers &…
  • Create Registration and Login Form in Node.js & MySQL
  • PHP Registration Form - Create Registration Form Using PHP

Filed Under: PHP

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Reader Interactions

Comments

  1. Gail says

    April 11, 2020 at 5:16 am

    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
    • Noor Khan says

      April 11, 2020 at 4:18 pm

      you can call process.php using ajax script.
      and you can read How to register with validation in PHP.
      . then you will easily insert data into the database.

      Reply
  2. Mohamed ali says

    April 18, 2020 at 10:16 pm

    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
    • Mohamed ali says

      April 18, 2020 at 10:20 pm

      I’m sorry I get it now, it’s a self-defined function to perform certain string operations,
      thank’s man.

      Reply
    • Noor Khan says

      April 19, 2020 at 6:52 pm

      Ali, Thnks for commenting.

      Reply
  3. bheem singh says

    February 2, 2021 at 7:50 pm

    hello bro i want talk so please reply me

    Reply
    • Noor Khan says

      February 2, 2021 at 8:42 pm

      Sure, We can talk.. please put your query

      Reply
    • rohit says

      January 5, 2022 at 7:09 pm

      yes this blog is very helpful

      Reply
  4. marathitracks says

    April 24, 2021 at 5:59 pm

    The content is awesome that should be appreciated all around the globe.

    Reply
  5. fb88tv says

    June 21, 2021 at 11:53 pm

    This is very interesting, You’re a very skilled blogger.

    I have joined your feed and look forward to seeking more of your
    excellent post. Also, I have shared your web site
    in my social networks!

    Reply
  6. Khalid says

    August 15, 2021 at 10:31 pm

    Hello , Thank you for this valuable contribution
    But this does not work, when I click on register now, it takes me to the 403 forbidden page.

    Reply
    • Md Nurullah says

      August 21, 2021 at 6:42 pm

      please, recheck your code & execute it again. it will work currectly

      Reply
  7. Tomar Rathi says

    August 20, 2021 at 2:58 pm

    Thank your solving my Problem. You are really appreciated.

    Reply
    • Md Nurullah says

      August 21, 2021 at 6:48 pm

      You most welcome..

      Reply
  8. Ranibowking says

    September 19, 2021 at 11:17 pm

    I have to assure you that you are doing a great work here. Thanks greatly

    Reply
  9. Ronnie Ray says

    January 11, 2022 at 12:08 am

    It’s hard but you make it simple with your skill. Good job bro

    Reply
  10. Rupam Sarmah says

    January 12, 2022 at 3:00 am

    I have some queries… Can we talk in mail

    Reply
    • Md Nurullah says

      March 12, 2022 at 4:10 pm

      Hello Rupam Sarmah,

      You can send your queries to our mail id – codingstatus@gmail.com

      Reply
      • Rupam Sarmah says

        March 21, 2022 at 10:06 pm

        Kindly Check Your mailbox…

        Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Follow us

  • facebook
  • twitter
  • linkedin

Recent Posts

  • PHP Interview Questions and Answers
  • Upload Multiple Files to Store in MySQL Database Using PHP
  • How to Insert Data Using Ajax in PHP
  • SQL Join 3 Tables – Join Query for Three Tables
  • Load Records on Select Box using Ajax, PHP & MySQL
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2022 CodingStatus - All Rights Reserved