Lesson 6 of 8
Input Validation - filter_var & Custom Validators
Robust input validation is your first line of defense. PHP's filter_var covers standard formats; custom validators handle business rules. Organising validators into a Validator class makes rules reusable, testable, and easy to maintain across forms.
filter_var Filters & Custom Validator Class
<?php
declare(strict_types=1);
// ── filter_var - validate ──────────────────────────────────────
// Returns FALSE on failure (not null or "false")
$email = filter_var("alice@example.com", FILTER_VALIDATE_EMAIL);
$ip = filter_var("192.168.1.1", FILTER_VALIDATE_IP);
$url = filter_var("https://php.net", FILTER_VALIDATE_URL);
$int = filter_var("42", FILTER_VALIDATE_INT);
$float = filter_var("3.14", FILTER_VALIDATE_FLOAT);
$bool = filter_var("true", FILTER_VALIDATE_BOOLEAN);
// With options
$age = filter_var("25", FILTER_VALIDATE_INT, [
"options" => ["min_range" => 18, "max_range" => 120]
]);
// Returns 25 or false
// ── filter_var - sanitise (transform) ─────────────────────────
// These return the cleaned string (never false)
$safeStr = filter_var("<b>Hello</b>", FILTER_SANITIZE_SPECIAL_CHARS);
$safeUrl = filter_var("https://php.net", FILTER_SANITIZE_URL);
$safeInt = filter_var("42abc", FILTER_SANITIZE_NUMBER_INT); // "42"
// ── Custom Validator class ─────────────────────────────────────
class Validator {
private array $errors = [];
public function required(string $field, mixed $value, string $label): static {
if ($value === null || trim((string) $value) === "") {
$this->errors[$field] = "$label is required.";
}
return $this;
}
public function minLength(string $field, string $value, int $min, string $label): static {
if (!isset($this->errors[$field]) && mb_strlen(trim($value)) < $min) {
$this->errors[$field] = "$label must be at least $min characters.";
}
return $this;
}
public function maxLength(string $field, string $value, int $max, string $label): static {
if (!isset($this->errors[$field]) && mb_strlen($value) > $max) {
$this->errors[$field] = "$label must be $max characters or fewer.";
}
return $this;
}
public function email(string $field, string $value): static {
if (!isset($this->errors[$field]) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->errors[$field] = "Please enter a valid email address.";
}
return $this;
}
public function url(string $field, string $value): static {
if (!isset($this->errors[$field]) && !filter_var($value, FILTER_VALIDATE_URL)) {
$this->errors[$field] = "Please enter a valid URL.";
}
return $this;
}
public function regex(string $field, string $value, string $pattern, string $message): static {
if (!isset($this->errors[$field]) && !preg_match($pattern, $value)) {
$this->errors[$field] = $message;
}
return $this;
}
public function inList(string $field, mixed $value, array $allowed, string $label): static {
if (!in_array($value, $allowed, true)) {
$this->errors[$field] = "$label must be one of: " . implode(", ", $allowed) . ".";
}
return $this;
}
public function passes(): bool { return empty($this->errors); }
public function fails(): bool { return !empty($this->errors); }
public function errors(): array { return $this->errors; }
public function first(string $field): ?string { return $this->errors[$field] ?? null; }
}
// Usage - readable and chainable
$v = new Validator();
$v->required("title", $_POST["title"] ?? "", "Title")
->minLength("title", $_POST["title"] ?? "", 3, "Title")
->maxLength("title", $_POST["title"] ?? "", 200, "Title")
->required("email", $_POST["email"] ?? "", "Email")
->email("email", $_POST["email"] ?? "")
->inList("status", $_POST["status"] ?? "", ["draft","published"], "Status");
if ($v->fails()) {
$errors = $v->errors();
// Re-render form
}Quick Quiz
Tip
Tip
Practice Input Validation filtervar Custom Validators in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Input Validation - filter_var & Custom Validators
Practice Task
Note
Practice Task - (1) Write a working example of Input Validation filtervar Custom Validators from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Input Validation filtervar Custom Validators is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?