In this article, we will learn how to validate a form using PHP. when the user submits the form, there are many chances that the user can enter wrong data, it may have security problems, so before inserting it into the database table, we must first validate the data and then insert it into the database.


Example

Let's make an HTML form and validate it


index.php

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>PHP Form Validation</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    </head>
    <style type="text/css">
        .container {
            max-width: 700px;
            margin: 50px auto;
        }
        form {
            border: 1px solid #000000;
            background: #ecf5fc;
            padding: 40px 50px 45px;
        }
        .form-control:focus {
            border-color: #000;
            box-shadow: none;
        }
        .error {
            color: red;
            font-weight: 400;
            display: block;
            padding: 6px 0;
            font-size: 14px;
        }
        .form-control.error {
            border-color: red;
            padding: .375rem .75rem;
        }
    </style>
    <body>
        <div class="container mt-5">
            <!-- Form validation script -->
            <?php include('form_validation.php'); ?>
            <!-- Contact form -->
            <form action="" method="post">
                <div class="form-group row">
                    <label class="col-sm-4 col-form-label">Name</label>
                    <div class="col-sm-8">
                        <input type="text" name="name" class="form-control">
                        <!-- Error -->
                        <?php echo $nameEmptyErr; ?>
                        <?php echo $nameErr; ?>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-sm-4 col-form-label">Email</label>
                    <div class="col-sm-8">
                        <input type="email" name="email" class="form-control">
                        <!-- Error -->
                        <?php echo $emailEmptyErr; ?>
                        <?php echo $emailErr; ?>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-sm-4 col-form-label">Education</label>
                    <div class="col-sm-8">
                        <select id="education" name="education" class="form-control">
                            <option selected="" disabled>...</option>
                            <option value="Graduation">Graduation</option>
                            <option value="Post Graduation">Post Graduation</option>
                        </select>
                        <!-- Error -->
                        <?php echo $educationEmptyErr; ?>
                    </div>
                </div>

                <fieldset class="form-group">
                    <div class="row">
                        <legend class="col-form-label col-sm-4 pt-0">Gender</legend>
                        <div class="col-sm-8">
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" id="male" name="gender" value="Male" class="custom-control-input">
                                <label class="custom-control-label" for="male">Male</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                                <input type="radio" id="female" name="gender" value="Female" class="custom-control-input">
                                <label class="custom-control-label" for="female">Female</label>
                            </div>
                            <!-- Error -->
                            <?php echo $genderEmptyErr; ?>
                        </div>
                    </div>
                </fieldset>
                <div class="form-group row">
                    <div class="col-sm-4">Hobbies</div>
                    <div class="col-sm-8">
                        <div class="custom-control custom-checkbox custom-control-inline">
                            <input type="checkbox" name="hoby[]" value="Drawing" class="custom-control-input" id="drawing">
                            <label class="custom-control-label" for="drawing">Drawing</label>
                        </div>
                        <div class="custom-control custom-checkbox custom-control-inline">
                            <input type="checkbox" name="hoby[]" value="Singing" class="custom-control-input" id="singing">
                            <label class="custom-control-label" for="singing">Singing</label>
                        </div>
                        <div class="custom-control custom-checkbox custom-control-inline">
                            <input type="checkbox" name="hoby[]" value="Dancing" class="custom-control-input" id="dancing">
                            <label class="custom-control-label" for="dancing">Dancing</label>
                        </div>
                        <!-- Error -->
                        <?php echo $hobyEmptyErr; ?>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-sm-4 col-form-label">Comment</label>
                    <div class="col-sm-8">
                        <textarea class="form-control" name="comment" id="comment" rows="4"></textarea>
                        <!-- Error -->
                        <?php echo $commentEmptyErr; ?>
                    </div>
                </div>

                <div class="form-group row">
                    <div class="col-sm-12 mt-3">
                        <button type="submit" name="submit" class="btn btn-primary btn-block">Submit</button>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>


form_validation.php

<?php

// Error messages
$nameEmptyErr = "";
$emailEmptyErr = "";
$educationEmptyErr = "";
$genderEmptyErr = "";
$hobyEmptyErr = "";
$commentEmptyErr = "";
$nameErr = "";
$emailErr = "";

if (isset($_POST["submit"])) {
    // Set form variables
    $name = checkInput($_POST["name"]);
    $email = checkInput($_POST["email"]);

    if (!empty($_POST["education"])) {
        $education = checkInput($_POST["education"]);
    }
    if (!empty($_POST["gender"])) {
        $gender = checkInput($_POST["gender"]);
    }
    if (!empty($_POST["hoby"])) {
        $hoby = $_POST["hoby"];
    }

    $comment = checkInput($_POST["comment"]);

    // Name validation
    if (empty($name)) {
        $nameEmptyErr = '<div class="error">Name field can not be empty.</div>';
    } // Allow letters and white space 
    else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
        $nameErr = '<div class="error">Only letters and white space allowed.</div>';
    } else {
        echo $name . '<br>';
    }

    // Email validation
    if (empty($email)) {
        $emailEmptyErr = '<div class="error">Email field can not be empty.</div>';
    } // E-mail format validation
    else if (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $email)) {
        $emailErr = '<div class="error">Email format is not valid.</div>';
    } else {
        echo $email . '<br>';
    }

    # code...
    // Select option validation
    if (empty($education)) {
        $educationEmptyErr = '<div class="error">Tell us about your education.</div>';
    } else {
        echo $education . '<br>';
    }


    // Radio button validation
    if (empty($gender)) {
        $genderEmptyErr = '<div class="error">Specify your gender.</div>';
    } else {
        echo $gender . '<br>';
    }


    // Checkbox validation
    if (!empty($hoby)) {
        foreach ($_POST['hoby'] as $val) {
            echo $val . '<br>';
        }
    } else {
        $hobyEmptyErr = '<div class="error">What are your hobbies.</div>';
    }

    // Text-area validation
    if (empty($comment)) {
        $commentEmptyErr = '<div class="error">This field is required.</div>';
    } else {
        echo $comment . '<br>';
    }
}

function checkInput($input) {
    $input = trim($input);
    $input = stripslashes($input);
    $input = htmlspecialchars($input);
    return $input;
}

?>


Output:








Download source code

Are you facing problems in understanding this article? download source code now