PHP Form Validation
In this page:
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
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email";
} else {
echo "Invalid email";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$_POST['email'] = "";
if (empty($_POST['email'])) {
echo "Email is required";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$email = "[email protected]";
var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
?>
Login to try C/C++/Java/PHP code in the editor
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
$age = "25abc";
if (is_numeric($age) && $age > 0) {
echo "Valid";
} else {
echo "Invalid numeric input";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$password = "abc";
if (strlen($password) < 8) {
echo "Password must be at least 8 characters";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: