PHP Form Validation

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.

You should also learn the following examples –

1. Create a folder structure

You should also create the following folder structure

  myform/
    |__script.php
    |__form.php
    |

2. Create an HTML Form

This PHP script creates an HTML registration form with Bootstrap styling, includes a validation script, and handles form submissions, displaying validation errors and success messages.

File Name – form.php

<?php

include('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>

</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>

Explanation –

  1. The HTML form is created with Bootstrap styling, featuring input fields for first name, last name, email, password, and confirm password.
  2. PHP variables ($set_firstName, $set_lastName, $set_email) are used to retain valid input values after submission.
  3. Validation error messages are displayed for each input field ($fnameErr, $lnameErr, $emailErr, $passErr, $cpassErr).
  4. The form action is set to the current PHP script (htmlspecialchars($_SERVER["PHP_SELF"])) for form submission.
  5. Upon successful submission, a success message ($valid) is displayed.
  6. The form includes a “Register Now” button with the name attribute set to “register” for form processing.
  7. Bootstrap and jQuery libraries are linked for styling and interactive features.

2. PHP Validation Script

This PHP script validates a registration form, checking first name, last name, email, password, and confirm password using regular expressions. If all validations pass, a success message is set, and input values are sanitized; otherwise, error messages are displayed, and input values are retained for correction.

File Name – 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;
}
?>

Explanation –

  1. The PHP script initializes error messages and default values for input fields.
  2. Input values are extracted from the POST request using extract($_POST).
  3. The script validates first name, last name, email, password, and confirm password using regular expressions.
  4. Validation errors are assigned to corresponding error variables ($fnameErr, $lnameErr, etc.).
  5. If all validations pass, a success message ($valid) is set, and input values are sanitized using the legal_input function.
  6. The legal_input function trims, strips slashes, and converts special characters to HTML entities for input sanitization.
  7. If any validation fails, the input values are set to the provided values to maintain user input for correction.

8 thoughts on “PHP Form Validation”

  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?

  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.

Comments are closed.