Required Field Validator

51


 <html>
<body>
<h1><b><center>PHP Program for Required Field Validator</center></b></h1>
<?php
$nameErr = $emailErr = $websiteErr = $passwordErr = $genderErr = "";
$name = $email = $gender = $comment = $website = "";

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        if (!preg_match("/^[a-zA-Z_]*$/", $name)) {
            $nameErr = "Invalid Name";
        }
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Enter a valid email address";
        }
    }

    if (empty($_POST["website"])) {
        $websiteErr = "Website is required";
    } else {
        $website = test_input($_POST["website"]);
    }

    if (empty($_POST["gender"])) {
        $genderErr = "Gender is required";
    } else {
        $gender = test_input($_POST["gender"]);
    }

    if (empty($_POST["password"])) {
        $passwordErr = "Password is required";
    } else {
        $password = test_input($_POST["password"]);
        if (!preg_match("/^(?=.*[!@#$%^&_])(?=.*[0-9])(?=.*[A-Z]).{7,}$/", $password)) {
            $passwordErr = "Invalid password";
        }
    }

    if (empty($_POST["comment"])) {
        $comment = "";
    } else {
        $comment = test_input($_POST["comment"]);
    }
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
    NAME: <input type="text" name="name">
    <span class="error"><font color="RED">* <?php echo $nameErr; ?></font></span><br><br>

    EMAIL: <input type="text" name="email">
    <span class="error"><font color="RED">* <?php echo $emailErr; ?></font></span><br><br>

    WEBSITE: <input type="text" name="website">
    <span class="error"><font color="RED">* <?php echo $websiteErr; ?></font></span><br><br>

    COMMENT: <input type="text" name="comment"><br><br>

    PASSWORD: <input type="password" name="password">
    <span class="error"><font color="RED">* <?php echo $passwordErr; ?></font></span><br><br>

    GENDER:
    <input type="radio" name="gender" value="Female"> Female
    <input type="radio" name="gender" value="Male"> Male
    <span class="error"><font color="RED">* <?php echo $genderErr; ?></font></span><br><br>

    <input type="submit" name="submit" value="Submit">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    echo "NAME: " . $name . "<br>";
    echo "EMAIL: " . $email . "<br>";
    echo "WEBSITE: " . $website . "<br>";
    echo "COMMENT: " . $comment . "<br>";
    echo "GENDER: " . $gender . "<br>";
}
?>
</body>
</html>