Validation means checking that the data is what you expect before you use it. It answers “is this acceptable?” and gives a yes or no.
Text length
<?php
$name = "A";
if (mb_strlen($name) < 2 || mb_strlen($name) > 50) {
echo "Name must be between 2 and 50 characters.";
}
Name must be between 2 and 50 characters.
Use mb_strlen() so letters outside basic English count as one character each.
<?php
$emails = ["isha@example.com", "isha@", "not an email"];
foreach ($emails as $email) {
$valid = filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
echo $email . ": " . ($valid ? "valid" : "invalid") . "\n";
}
isha@example.com: valid
isha@: invalid
not an email: invalid
FILTER_VALIDATE_EMAIL checks the shape of an address. It cannot tell you that the mailbox exists. The only real proof is to send a confirmation email.
Whole numbers in a range
<?php
$age = "17";
$options = ["options" => ["min_range" => 18, "max_range" => 120]];
$value = filter_var($age, FILTER_VALIDATE_INT, $options);
if ($value === false) {
echo "Age must be a whole number from 18 to 120.";
}
Age must be a whole number from 18 to 120.
A choice from a list
<?php
$plan = "gold";
$allowed = ["free", "pro", "team"];
if (!in_array($plan, $allowed, true)) {
echo "Invalid plan.";
}
Invalid plan.
A date
<?php
function isValidDate(string $date): bool
{
$d = DateTime::createFromFormat("Y-m-d", $date);
return $d !== false && $d->format("Y-m-d") === $date;
}
var_dump(isValidDate("2026-02-28"));
var_dump(isValidDate("2026-02-31"));
bool(true)
bool(false)
A URL
<?php
var_dump(filter_var("https://example.com", FILTER_VALIDATE_URL) !== false);
var_dump(filter_var("example", FILTER_VALIDATE_URL) !== false);
bool(true)
bool(false)
FILTER_VALIDATE_URL also accepts schemes such as javascript: or ftp:. If the URL will be a link, check the scheme yourself.
<?php
function isWebUrl(string $url): bool
{
return filter_var($url, FILTER_VALIDATE_URL) !== false
&& in_array(parse_url($url, PHP_URL_SCHEME), ["http", "https"], true);
}
var_dump(isWebUrl("https://example.com"));
var_dump(isWebUrl("javascript:alert(1)"));
bool(true)
bool(false)
Pattern matching
For fixed formats such as a PIN code or a username, use a regular expression.
<?php
function isValidUsername(string $name): bool
{
return preg_match('/^[a-z0-9_]{3,20}$/i', $name) === 1;
}
var_dump(isValidUsername("isha_29"));
var_dump(isValidUsername("a b"));
bool(true)
bool(false)
The validation habit
- Read the value with a default.
trim()it.- Check each rule and collect the errors (see Validation Errors).
- Only if there are no errors, use the data.