Lesson 34 of 50 – PHP Form Validation
68%

PHP Form Validation

Form validation is the process of checking submitted data before using or saving it. PHP performs server-side validation to ensure that required fields are filled in and that values have the expected format.

1. What Is Form Validation?

Form validation checks whether submitted information meets the application's requirements.

Common validation tasks include:

  • Checking whether a field is empty.
  • Validating an email address.
  • Checking the length of a name or password.
  • Validating numbers and mobile numbers.
  • Checking whether a selected option is allowed.

Example:

<?php
$name = "Rahul";

if (trim($name) === "") {
    echo "Name is required.";
} else {
    echo "Name is valid.";
}
?>
Output:
Name is valid.

Server-side validation is essential because browser validation can be bypassed.

2. Validating Required Fields

A required field must contain a value before the form can be accepted.

<?php
$name = "   ";

if (trim($name) === "") {
    echo "Name is required.";
} else {
    echo "Name accepted.";
}
?>
Output:
Name is required.

The trim() function removes whitespace from the beginning and end of a string. This helps prevent a user from submitting only spaces.

Another example:

<?php
$email = "";

if (trim($email) === "") {
    echo "Email is required.";
}
?>
Output:
Email is required.
3. Validating an Email Address

PHP provides filter_var() with FILTER_VALIDATE_EMAIL to check whether an email address has a valid format.

<?php
$email = "student@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}
?>
Output:
Valid email address.

Invalid email example:

<?php
$email = "studentexample.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email address.";
} else {
    echo "Invalid email address.";
}
?>
Output:
Invalid email address.

Email format validation does not prove that the mailbox exists. Applications may need an email verification process as well.

4. Validating Numbers

Use is_numeric() to check whether a value is a number or a numeric string.

<?php
$age = "21";

if (is_numeric($age)) {
    echo "Age is numeric.";
} else {
    echo "Please enter a number.";
}
?>
Output:
Age is numeric.

Validate a range:

<?php
$age = 20;

if (
    filter_var($age, FILTER_VALIDATE_INT) !== false &&
    $age >= 1 &&
    $age <= 120
) {
    echo "Valid age.";
} else {
    echo "Invalid age.";
}
?>
Output:
Valid age.

Range validation ensures that a value is not only numeric but also within the permitted limits.

5. Validating a Mobile Number

If your application expects an Indian mobile number containing exactly 10 digits, you can validate its format using a regular expression.

<?php
$mobile = "9876543210";

if (preg_match('/^[0-9]{10}$/', $mobile)) {
    echo "Mobile number format is valid.";
} else {
    echo "Enter a 10-digit mobile number.";
}
?>
Output:
Mobile number format is valid.

Invalid example:

<?php
$mobile = "98765";

if (preg_match('/^[0-9]{10}$/', $mobile)) {
    echo "Valid mobile number.";
} else {
    echo "Invalid mobile number.";
}
?>
Output:
Invalid mobile number.

This checks the format only. It does not verify that the number is active or belongs to a particular person.

6. Validating a Dropdown Selection

Never assume that a dropdown's submitted value is valid just because the browser displayed predefined options. A user can send a different value manually.

<?php
$course = $_POST['course'] ?? '';

$allowedCourses = [
    'PHP',
    'JavaScript',
    'Python'
];

if (in_array($course, $allowedCourses, true)) {
    echo "Selected course: " .
        htmlspecialchars($course, ENT_QUOTES, 'UTF-8');
} else {
    echo "Please select a valid course.";
}
?>

The submitted course is accepted only if it matches one of the allowed values.

Example form:

<form method="post" action="">
    <label for="course">Choose Course:</label>

    <select name="course" id="course" required>
        <option value="">Select a course</option>
        <option value="PHP">PHP</option>
        <option value="JavaScript">JavaScript</option>
        <option value="Python">Python</option>
    </select>

    <button type="submit">Submit</button>
</form>
7. Validating Password Length

You can check whether a password meets a minimum length requirement using strlen().

<?php
$password = "mypassword123";

if (strlen($password) >= 8) {
    echo "Password length is acceptable.";
} else {
    echo "Password must contain at least 8 bytes.";
}
?>
Output:
Password length is acceptable.

For ordinary ASCII passwords, strlen() counts bytes and corresponds to the number of characters. For multibyte text, byte length and character count can differ.

In a real application, validate password requirements on the server and store passwords using password_hash(), not as plain text. Use password_verify() during login.

8. Complete PHP Form Validation Example

Save this example as validation_form.php. It validates a student's name, email, and mobile number on the server.

<?php
$name = '';
$email = '';
$mobile = '';
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $mobile = trim($_POST['mobile'] ?? '');

    // Validate name
    if ($name === '') {
        $errors[] = 'Name is required.';
    } elseif (strlen($name) > 100) {
        $errors[] = 'Name must not exceed 100 bytes.';
    }

    // Validate email
    if ($email === '') {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Enter a valid email address.';
    }

    // Validate mobile
    if (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $errors[] = 'Enter a valid 10-digit mobile number.';
    }

    if (count($errors) === 0) {
        $success = 'Form submitted successfully.';
    }
}
?>

<form method="post" action="">
    <label for="name">Student Name:</label>
    <input
        type="text"
        id="name"
        name="name"
        maxlength="100"
        value="<?= htmlspecialchars(
            $name,
            ENT_QUOTES,
            'UTF-8'
        ) ?>"
        required
    >

    <br><br>

    <label for="email">Email:</label>
    <input
        type="email"
        id="email"
        name="email"
        value="<?= htmlspecialchars(
            $email,
            ENT_QUOTES,
            'UTF-8'
        ) ?>"
        required
    >

    <br><br>

    <label for="mobile">Mobile Number:</label>
    <input
        type="tel"
        id="mobile"
        name="mobile"
        pattern="[0-9]{10}"
        maxlength="10"
        value="<?= htmlspecialchars(
            $mobile,
            ENT_QUOTES,
            'UTF-8'
        ) ?>"
        required
    >

    <br><br>

    <button type="submit">Submit Form</button>
</form>

<?php
if (count($errors) > 0) {
    echo "<h4>Please correct these errors:</h4><ul>";

    foreach ($errors as $error) {
        echo "<li>" .
            htmlspecialchars($error, ENT_QUOTES, 'UTF-8') .
            "</li>";
    }

    echo "</ul>";
}

if ($success !== '') {
    echo "<p>" .
        htmlspecialchars($success, ENT_QUOTES, 'UTF-8') .
        "</p>";
}
?>

The example collects validation errors and displays them together. It preserves the submitted values after validation fails.

For a production form that changes server data, add CSRF protection and use prepared statements when saving information to a database.

9. Validation vs. Sanitization

Validation and sanitization have different purposes.

  • Validation: Checks whether input meets a rule, such as a valid email format.
  • Sanitization: Transforms or filters data according to a particular requirement.
  • Output escaping: Encodes data for its output context, such as HTML.

Validation example:

<?php
$email = "student@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Email is valid.";
} else {
    echo "Email is invalid.";
}
?>

Output escaping example:

<?php
$name = '<script>alert("Hello")</script>';

echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
?>

Escaping converts special characters so the string is displayed as text instead of being interpreted as HTML markup.

Do not rely on sanitization alone. Validate data according to business rules, escape output for its context, and use prepared statements for database queries.

Practice Assignments
  1. Check whether a name field is empty.
  2. Validate an email address using filter_var().
  3. Check whether a value is numeric.
  4. Validate a 10-digit mobile number.
  5. Check whether a password contains at least 8 bytes.
  6. Validate a dropdown selection against allowed courses.
  7. Create a registration form with three validation rules.
  8. Display all validation errors together.
  9. Explain the difference between validation, sanitization, and output escaping.

🧠 Quick Quiz

1. Which PHP function can validate an email format?




2. Why is server-side validation necessary?




3. Which function escapes special HTML characters?