← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 2 of 8

PHP Form Validation

Validating Emails

Server-side validation checks that submitted form data actually meets your requirements — correct format, required fields present, values within range — and must always be done even if you also validate in JavaScript, since client-side checks can be bypassed entirely.

Example: Validating Emails

php
<?php
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email";
} else {
    echo "Invalid email";
}
?>

Validating Integers

empty() and isset() are the first line of defense for required fields, letting you reject a submission immediately if a mandatory field like an email address is missing or blank.

Example: Validating Integers

php
<?php
$_POST['email'] = "";
if (empty($_POST['email'])) {
    echo "Email is required";
}
?>

Checking Input Length

filter_var($value, FILTER_VALIDATE_EMAIL) and similar filter_var() calls provide built-in validation for common formats like emails and URLs, saving you from writing fragile validation logic by hand.

Example: Checking Input Length

php
<?php
$email = "[email protected]";
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
?>

Custom Format Validation

Numeric fields need explicit checks like is_numeric() plus range checks, since PHP's loose typing means a string like 5abc can behave unpredictably in arithmetic if you don't validate its shape first.

Example: Custom Format Validation

php
<?php
$age = "25abc";
if (is_numeric($age) && $age > 0) {
    echo "Valid";
} else {
    echo "Invalid numeric input";
}
?>

Collecting Validation Errors

Good validation gives specific, actionable feedback (e.g. 'Password must be at least 8 characters') rather than a single generic 'invalid input' message, which frustrates users trying to figure out what actually went wrong.

Example: Collecting Validation Errors

php
<?php
$password = "abc";
if (strlen($password) < 8) {
    echo "Password must be at least 8 characters";
}
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.