PHP Form Validation for Name, Email, URL, Phone, and Gender (with Code Examples)

Last updated 4 months ago | 346 views 75     5

Tags:- PHP

Introduction: Why PHP Form Validation Is Crucial

Form validation is a must-have feature in any PHP-powered web application. Whether you're building a contact form, registration system, or a feedback portal, you need to ensure that:

  • Users provide valid and complete data

  • Malicious inputs are filtered and sanitized

  • Your backend remains safe and predictable

This guide walks you through validating name, email, phone number, website URL, and gender fields using PHP. We’ll cover basic logic, provide code samples, and wrap up with a full working example.


Key PHP Form Validation Concepts

Sanitize Input

Before validating anything, you must clean up the user input:

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

This prevents injection attacks and removes whitespace.


Step-by-Step PHP Form Validation

1. Validate Name

if (empty($name)) {
    $nameErr = "Name is required";
} elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
    $nameErr = "Only letters and white space allowed";
}

2. Validate Email

if (empty($email)) {
    $emailErr = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format";
}

3. Validate Website (URL)

if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) {
    $websiteErr = "Invalid URL format";
}

4. Validate Phone

if (empty($phone)) {
    $phoneErr = "Phone number is required";
} elseif (!preg_match("/^[0-9]{10}$/", $phone)) {
    $phoneErr = "Phone must be exactly 10 digits";
}

5. Validate Gender

if (empty($gender)) {
    $genderErr = "Gender is required";
}

✅ Full Example: PHP Form Validation Code

PHP Backend

<?php
$name = $email = $website = $phone = $gender = "";
$nameErr = $emailErr = $websiteErr = $phoneErr = $genderErr = "";

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = clean_input($_POST["name"]);
    $email = clean_input($_POST["email"]);
    $website = clean_input($_POST["website"]);
    $phone = clean_input($_POST["phone"]);
    $gender = clean_input($_POST["gender"]);

    // Name validation
    if (empty($name)) {
        $nameErr = "Name is required";
    } elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
        $nameErr = "Only letters and white space allowed";
    }

    // Email validation
    if (empty($email)) {
        $emailErr = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    }

    // Website URL validation
    if (!empty($website) && !filter_var($website, FILTER_VALIDATE_URL)) {
        $websiteErr = "Invalid URL";
    }

    // Phone number validation
    if (empty($phone)) {
        $phoneErr = "Phone is required";
    } elseif (!preg_match("/^[0-9]{10}$/", $phone)) {
        $phoneErr = "Phone must be 10 digits";
    }

    // Gender validation
    if (empty($gender)) {
        $genderErr = "Gender is required";
    }
}
?>

HTML Form

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name: <input type="text" name="name" value="<?php echo $name; ?>">
    <span style="color:red">* <?php echo $nameErr; ?></span><br><br>

    Email: <input type="text" name="email" value="<?php echo $email; ?>">
    <span style="color:red">* <?php echo $emailErr; ?></span><br><br>

    Website: <input type="text" name="website" value="<?php echo $website; ?>">
    <span style="color:red"><?php echo $websiteErr; ?></span><br><br>

    Phone: <input type="text" name="phone" value="<?php echo $phone; ?>">
    <span style="color:red">* <?php echo $phoneErr; ?></span><br><br>

    Gender:
    <input type="radio" name="gender" value="Male" <?php if ($gender=="Male") echo "checked"; ?>> Male
    <input type="radio" name="gender" value="Female" <?php if ($gender=="Female") echo "checked"; ?>> Female
    <input type="radio" name="gender" value="Other" <?php if ($gender=="Other") echo "checked"; ?>> Other
    <span style="color:red">* <?php echo $genderErr; ?></span><br><br>

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

⚠️ Tips & Common Pitfalls

  • Always sanitize inputs using htmlspecialchars and trim.

  • Never trust user input—even if you're using JavaScript validation.

  • Use filter_var() for standard formats (email, URL).

  • Regex is best for custom formats like phone numbers or names.

  • Don’t forget to check for empty fields before validating format.


Comparison Table

Field Required Validation Technique
Name ✅ Yes Regex (/^[a-zA-Z-' ]*$/)
Email ✅ Yes filter_var with FILTER_VALIDATE_EMAIL
Website ❌ No filter_var with FILTER_VALIDATE_URL
Phone ✅ Yes Regex (/^[0-9]{10}$/)
Gender ✅ Yes Radio selection

✅ Conclusion

Form validation in PHP is essential for data integrity, security, and user experience. By following the validation techniques discussed above, you can avoid incorrect submissions and handle user input gracefully.

Best Practices:

  • Always sanitize and validate inputs server-side.

  • Use PHP’s built-in filter_var() for common data types.

  • Combine regex with conditionals for custom formats.

  • Give users helpful error messages for each field.