Form Validation With PHP Regular Expression

Form Validation With PHP Regular Expression

Form Validation With PHP Regular Expression

Form validation is a crucial part of web development to ensure that the data provided by users is accurate and conforms to the expected format. In this guide, we will demonstrate how to validate a form using PHP and regular expressions (regex). We’ll also use Bootstrap for styling to make the form visually appealing.

Step 1: Connect Bootstrap CSS and JS CDN

Start by connecting the Bootstrap CDN for styling and the required JS libraries.

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

Step 2: Create the Form HTML

Here’s the HTML form that we will use to collect user input such as name, email, phone, and a message. The form uses the POST method to submit data securely.

  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" class="form" id="form">
       <div class="form-group ">
            <input type="name" required class="form-control" placeholder="Enter Your Name*" name="name" id="name">
            <span class="error"><?=$nameerror?$nameerror : "" ?></span>
       </div>
       <div class="form-group">
            <input type="email" required class="form-control" placeholder="Enter Your Email*" name="email" id="email">
            <span class="error"> <?=$emailerror?$emailerror : "" ?></span>
       </div>
       <div class="form-group">
            <input type="number" required class="form-control" placeholder="Enter Your Phone Number*" name="phone" id="phone">
            <span class="error"> <?=$phoneerror?$phoneerror : "" ?></span>
       </div>
        <div class="form-group">
            <textarea name="message" id="message" placeholder="Enter your Message" class="form-control"></textarea>
        </div>
        <div class="form-group">
             <input type="submit" name="send" id="submit" class="btn btn-success" value="send">
        </div>             
  </form> 

Step 3: Declare PHP Variables and Validate Fields

In your PHP file, declare the necessary variables to store the input values and error messages. Then, perform validation checks to ensure that all fields are filled, and the email and phone number follow the correct formats.

$name = $email = $phone = $message = $nameerror = $emailerror = $phoneerror = $messageerror = null;

Check all the field is empty or not. if empty then print a message

if ($_SERVER["REQUEST_METHOD"] == 'POST') {

    if (empty($_POST["name"])) {
        $nameerror = "Name is required";
    } else {
        $name = $_POST["name"];
    }
    if (empty($_POST["email"])) {
        $emailerror = "Email is required";
    } else {
        $email = $_POST["email"];

    }
    if (empty($_POST["phone"])) {
        $phoneerror = "Phone is required & Its must be Bangladesh Number";
    } else {
        $phone = $_POST["phone"];

        $pattern = '/^(?:\+88|88)?(01[3-9]\d{8})$/';

        if (preg_match($pattern, $phone) == 0) {
            $phoneerror = "Please Enter Valid Bangladesh Number";
        } else {
            $phone = $_POST["phone"];
        }
    }

    if (empty($_POST["message"])) {
        $messageerror = "";
    } else {
        $message = $_POST["message"];
    }

}

Step 4: Display User Input and Errors

After validating the form, display the input data and errors to the user.

        <h6>Output</h6>
        <table>
            <tr>
                <td>Name: </td>
                <td><?=$name?$name:""?></td>
            </tr>
            <tr>
                <td>Email: </td>
                <td><?=$email?$email:""?></td>
            </tr>
            <tr>
                <td>Phone: </td>
                <td><?=$phone?$phone:""?></td>
            </tr>
            <tr>
                <td>Message: </td>
                <td><?=$message?$message:""?></td>
            </tr>
        </table>   

Step 5: Explanation of Regular Expression for Phone Validation

We use a regular expression (regex) to validate a Bangladesh phone number. The pattern checks for phone numbers starting with the country code +88 or 88, followed by the mobile operator prefix (such as 013, 014, etc.) and then 8 digits.

After validating the form, display the input data and errors to the user.

$pattern = '/^(?:\+88|88)?(01[3-9]\d{8})$/';

This ensures that the number is properly formatted according to the Bangladesh standard.

Conclusion

By using regular expressions and PHP, you can ensure that the data submitted through your forms is valid. This example demonstrates basic form validation techniques, but you can expand it further by adding more complex validation logic as per your needs.

Explore more about PHP validation and regular expressions in the following articles:

Explore More: Mastering PHP Sessions: 3 Powerful Techniques for Starting, Destroying, and Setting Timeout, Boost Your Email System: Send Mail with PHP Mailer (Step-by-Step Guide), Master PHP Namespace: 3 Powerful Ways to Organize Your Code Like a Pro, 6 Step of Version Control: Basic Git Command for Beginners

Leave a Reply

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

Back To Top
Theme Mode