Form Validation in PHP for Beginners

Form validation in PHP is a crucial step to ensure that user input is clean, correct, and secure before processing or storing it in a database. This PHP tutorial for beginners covers server-side form validation techniques to check for required fields, valid email and phone number. You will learn how to handle form input validation in PHP and display custom validation error messages.

In this tutorial, we will develop a form in Bootstrap 5 and validate the form using PHP after the form is submitted. So, this will be server-side form validation without JavaScript.

Below is the screenshot of the Form

Form Validation in PHP

We will follow the below steps to complete our development:

  1. Develop a form using HTML and CSS with Bootstrap 5
  2. Write PHP code to add validation after form submission

Watch YouTube Video

Develop a form using HTML and CSS with Bootstrap 5

We will develop a simple form with input fields Name, Email and Phone using Bootstrap 5. You can add the Bootstrap 5 library from a CDN. The html code for this is given below:


                    <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Validation in PHP</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="style.css">
    </head>
    <h1>Form Validation in PHP</h1>
    <body>
        <form class="form1" action="" method="post">
            <div class="mb-3">
                <label for="name" class="form-label">Name</label>
                <input type="text" class="form-control" name="name" id="name" value=""
                    placeholder="Enter your name" />
                <div class="showErr"></div>
            </div>

            <div class="mb-3">
                <label for="email" class="form-label">Email</label>
                <input type="text" class="form-control" name="email" id="email" value=""
                    placeholder="Enter your email" />
                <div class="showErr"></div>
            </div>

            <div class="mb-3">
                <label for="phone" class="form-label">Phone</label>
                <input type="text" class="form-control" name="phone" id="phone" value=""
                    placeholder="Enter your phone" />
                <div class="showErr"></div>
            </div>
            <button type="submit" class="btn btn-primary" name="submit">
                Submit
            </button>
        </form>
    </body>
</html>

This is a simple form with three fields and a submit button. You can see that for each input, there is a place to display a validation error. For the name field, it is:


<div class="showErr"></div>

Our stylesheet is given below:


*{
    box-sizing: border-box;
}
.form1{
    width:40%;
    border:1px solid #a89595;
    border-radius: 10px;
    margin:auto;
    padding:10px;
}
h1{
    text-align: center;
}
.showErr{
    color:red;
}

Write PHP code to add validation after form submission

When the form is submitted, we will start validating the inputs using PHP code.

We will code for three types of input validations:

  1. Empty fields validation
  2. Email format validation
  3. Phone number validation

After the form is submitted, we will get the values of the input fields into variables and we will use variables to assign the validation errors. Once a validation fails, we will set a flag indicating that some validation failed.

Empty fields validation

We will check if the input values are empty by using the PHP empty() function.


<?php
$name = $email = $phone = "";
$nameErr = $emailErr = $phoneErr = "";
$succ_msg = "";
$errFlag = false;
if (isset($_POST['submit'])) {
    // when the form is submitted, validate the data
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);

    if (empty($name)) {
        $nameErr = "Name is Required";
        $errFlag = true;
    }

    if (empty($email)) {
        $emailErr = "Email is Required";
        $errFlag = true;
    } 

    if (empty($phone)) {
        $phoneErr = "Phone is Required";
        $errFlag = true;
    }

    if (!$errFlag) {
        // process the form, insert data into the database
        $succ_msg = "Form is validated successfully";
    }
}
    

Note that the error flag is initialized as false and it is made true when a validation fails. At the end, we are checking if the error flag is false, which means all validations are successful, so the form can be processed.

Email validation

We will use the PHP function filter_var() to validate if the email format is correct. filter_var() returns true if the email format is correct by using a filter FILTER_VALIDATE_EMAIL. So, our email validation code will be as follows:


if (empty($email)) {
    $emailErr = "Email is Required";
    $errFlag = true;
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Email is Invalid";
    $errFlag = true;
    }
}

Phone Number validation

We will use a regular expression for the phone number validation; it is given below:


$phone_regex = "/^[1-9][0-9]{9}$/";

The first digit should be any digit between 1 to 9 and the remaining 9 digits can be from 0 to 9. Total 10 digits. Then we will use the preg_match() function to verify if the input phone number matches the regular expression. If it does not, we give an error message. See the code below:


if (empty($phone)) {
    $phoneErr = "Phone is Required";
    $errFlag = true;
    }
else{
    $phone_regex = "/^[1-9][0-9]{9}$/";
    if (!preg_match($phone_regex, $phone)){
        $phoneErr = "Phone must be 10 digit with no leading zero";
        $errFlag = true;
    }
}

Now, we will display values in the value attributes of the input fields and the error messages in the form.


<input type="text" class="form-control" name="name" id="name" value="<?= $name ?>" placeholder="Enter your name" />
<div class="showErr"><?= $nameErr ?>
</div>

See the value attribute and the error message as displayed above. Same way, we can display them for the other two fields.

When all the validations are successful, we will process the form data, for example, you can insert the data into a database table. In this tutorial, we are just covering the validation part of it. So, we just need to display the success message now. We will write the code below just after the <form> tag.


<?php
if (!empty($succ_msg)) { ?>
            <div class="alert alert-success"><?= $succ_msg ?></div>
            <?php } ?>
    

ajax dropdown selected value in phpTest the Application

Before testing, make sure Apache and MySQL services are running in the XAMPP Control panel. In the browser, run index.php. You will see that the form is displayed. Test for empty values and also enter any values in the phone number and email, for example, just enter "test" and submit the form. You should see the error messages. If you enter valid values for name, phone and email, the form will be submitted successfully.

PHP form validation source codeDownload Source Code

You can download the source code from GitHub by clicking on the download button below:

Conclusion

In this PHP tutorial, we have learned how to validate a form using PHP. We validated empty fields, phone number and email. This is fully server-side validation without using JavaScript. You can check the related topics to learn how you can validate validate unique email in a registration form and insert the data into a database table after successful form validation.

Please write your comments/questions in the Comments section below. Your questions, doubts and suggestions are always welcome.

Post a Comment

Save my Name and Email id for future comments