The Analogy: The Customs Inspection Hall
Before goods enter a country, they pass through a customs inspection hall. Nothing gets waved through on trust: every shipment is checked against a set of rules before it is allowed past the barrier. Does it have the right paperwork? Is the declared category permitted? Is the quantity within limits? Only a shipment that satisfies every rule proceeds; anything failing is held at the barrier with a note explaining exactly what was wrong. Request validation is that inspection hall. Every piece of data arriving from a user's browser is a shipment of unknown provenance, and validation is the checkpoint it must clear before your application acts on it.
The inspector works from an explicit list of rules, one set per kind of goods. Perishables have different rules from electronics; a registration form has different rules from a search box. Each field of the incoming data is checked against the rules declared for it: this one is required, that one must look like an email, this password must be at least eight characters. The rules are written down in advance, not improvised, so every shipment of the same kind is judged by the same standard. Laravel expresses this as a rules array -- 'email' => 'required|email' -- read and applied uniformly.
When a shipment fails, the inspector does not simply reject it silently; they produce a clear manifest of every problem so the sender can fix it. "Missing certificate of origin; quantity exceeds limit." Good validation collects the failures per field and reports them back, so the user sees "email is invalid" and "password is too short" together, not one cryptic error at a time. This feedback loop is what turns a rejected form into a fixable one.
The failure mode is the inspector who trusts the shipment's own label. A crate marked "safe, pre-inspected, admit without checking" is exactly the crate that most needs inspecting, yet a lazy hall waves it through on the strength of its label. In software this is trusting client-side validation, or hidden form fields, or an is_admin flag the client sent, as if the browser were an honest inspector. The browser is not the customs hall; it is the sender, and the sender can forge any label. All meaningful validation must happen on the server, because that is the only barrier the user cannot walk around. Client-side checks improve the experience, but the server-side inspection is the one that actually protects the country.
Syntax or Core Structure
These plain-PHP illustrations model Laravel's validator: a rules array is applied to a data array, producing per-field errors. Rules are written as pipe-separated strings like required|email, and passes reports whether every rule held.
<?php
declare(strict_types=1);
final class Validator {
private array $errors = [];
public function __construct(private array $data, private array $rules) {}
public function passes(): bool {
foreach ($this->rules as $field => $ruleString) {
foreach (explode('|', $ruleString) as $rule) {
$this->apply($field, $rule);
}
}
return $this->errors === [];
}
public function errors(): array { return $this->errors; }
private function apply(string $field, string $rule): void {
[$name, $arg] = array_pad(explode(':', $rule, 2), 2, null);
$value = $this->data[$field] ?? null;
$ok = match ($name) {
'required' => $value !== null && $value !== '',
'email' => is_string($value) && str_contains($value, '@'),
'min' => is_string($value) && strlen($value) >= (int) $arg,
default => true,
};
if (!$ok) {
$this->errors[$field][] = $name;
}
}
}
$v = new Validator(
['name' => '', 'email' => 'nope', 'password' => 'abc'],
['name' => 'required', 'email' => 'required|email', 'password' => 'required|min:6']
);
echo 'passes: ', $v->passes() ? 'yes' : 'no', "\n";
foreach ($v->errors() as $field => $failed) {
echo "$field failed: ", implode(', ', $failed), "\n";
}
Output:
passes: no
name failed: required
email failed: email
password failed: min
Each field's pipe-separated rules are split and applied. The empty name fails required; nope is present so it passes required but fails email for lacking an @; the three-character password passes required but fails min:6. The validator collects all failures and passes returns no. This rules-array-to-errors shape is exactly how Laravel's Validator::make($data, $rules) works.
Technical Depth: Rules, Bailing, and Where Validation Belongs
A vocabulary of rules
Validators ship with a library of rules covering the common needs. A rule may take an argument after a colon, such as min:8.
| Rule | Passes when | Argument |
|---|---|---|
required | Value present and not empty | -- |
email | Looks like an email address | -- |
min | At least N characters (or value) | length |
max | At most N characters (or value) | length |
confirmed | Matches field_confirmation | -- |
in | One of a fixed set | list |
The passing path matters as much as the failing one, so it is worth confirming valid data clears the checkpoint cleanly.
<?php
declare(strict_types=1);
final class Validator {
private array $errors = [];
public function __construct(private array $data, private array $rules) {}
public function passes(): bool {
foreach ($this->rules as $field => $ruleString) {
foreach (explode('|', $ruleString) as $rule) { $this->apply($field, $rule); }
}
return $this->errors === [];
}
public function errors(): array { return $this->errors; }
private function apply(string $field, string $rule): void {
[$name, $arg] = array_pad(explode(':', $rule, 2), 2, null);
$value = $this->data[$field] ?? null;
$ok = match ($name) {
'required' => $value !== null && $value !== '',
'email' => is_string($value) && str_contains($value, '@'),
'min' => is_string($value) && strlen($value) >= (int) $arg,
default => true,
};
if (!$ok) { $this->errors[$field][] = $name; }
}
}
$v = new Validator(
['name' => 'Ada', 'email' => 'ada@x.com', 'password' => 'secret1'],
['name' => 'required', 'email' => 'required|email', 'password' => 'required|min:6']
);
echo 'passes: ', $v->passes() ? 'yes' : 'no', "\n";
echo 'error count: ', count($v->errors()), "\n";
Output:
passes: yes
error count: 0
With a real name, a valid-looking email, and a seven-character password, every rule holds, passes returns yes, and there are zero errors. Clean data flows straight through, which is the point: validation is a gate, not a wall.
Bailing on the first failure
Sometimes you want to stop checking a field after its first failure, so a user is not told their password is both missing and too short -- just that it is missing. Laravel calls this bail.
<?php
declare(strict_types=1);
final class BailValidator {
private array $errors = [];
public function __construct(private array $data, private array $rules) {}
public function validate(): array {
foreach ($this->rules as $field => $ruleString) {
foreach (explode('|', $ruleString) as $rule) {
if (!$this->check($field, $rule)) {
$this->errors[$field] = $rule;
break;
}
}
}
return $this->errors;
}
private function check(string $field, string $rule): bool {
[$name, $arg] = array_pad(explode(':', $rule, 2), 2, null);
$value = $this->data[$field] ?? null;
return match ($name) {
'required' => $value !== null && $value !== '',
'min' => is_string($value) && strlen($value) >= (int) $arg,
default => true,
};
}
}
$errors = (new BailValidator(
['password' => ''],
['password' => 'required|min:6']
))->validate();
foreach ($errors as $field => $rule) {
echo "$field stopped at: $rule\n";
}
Output:
password stopped at: required
The empty password fails required, so the break stops before min:6 is ever checked -- reporting only the most fundamental failure. This is cleaner feedback: telling someone their empty field is also too short is noise. Whether to bail or collect all failures is a deliberate choice per field.
Validation belongs on the server
The single most important rule is that validation must run on the server. Client-side JavaScript validation improves the experience by giving instant feedback, but it is trivially bypassed -- a user can disable JavaScript, edit the page, or send the request directly with a tool. The server is the only checkpoint the user cannot circumvent, so it must re-validate everything, treating the client's checks as a convenience, never as a guarantee.
Real World Example: Validating a Registration Form
A registration form is the classic validation case: a name, an email, and a password that must be long enough and confirmed. The validator below applies rules per field, bails on each field's first failure, and produces human-readable messages -- exactly the shape of a Laravel form request.
<?php
declare(strict_types=1);
final class Validator {
private array $errors = [];
private const MESSAGES = [
'required' => 'is required',
'email' => 'must be a valid email',
'min' => 'is too short',
'confirmed' => 'confirmation does not match',
];
public function __construct(private array $data, private array $rules) {}
public function validate(): bool {
foreach ($this->rules as $field => $ruleString) {
foreach (explode('|', $ruleString) as $rule) {
[$name, $arg] = array_pad(explode(':', $rule, 2), 2, null);
if (!$this->check($field, $name, $arg)) {
$this->errors[$field] = ucfirst($field) . ' ' . self::MESSAGES[$name];
break;
}
}
}
return $this->errors === [];
}
public function errors(): array { return $this->errors; }
private function check(string $field, string $name, ?string $arg): bool {
$value = $this->data[$field] ?? null;
return match ($name) {
'required' => $value !== null && $value !== '',
'email' => is_string($value) && str_contains($value, '@') && str_contains($value, '.'),
'min' => is_string($value) && strlen($value) >= (int) $arg,
'confirmed' => ($value ?? null) === ($this->data[$field . '_confirmation'] ?? null),
default => true,
};
}
}
$request = [
'name' => 'Ada',
'email' => 'ada-at-example',
'password' => 'short',
'password_confirmation' => 'different',
];
$v = new Validator($request, [
'name' => 'required|min:2',
'email' => 'required|email',
'password' => 'required|min:8|confirmed',
]);
if ($v->validate()) {
echo "registered\n";
} else {
echo "validation failed:\n";
foreach ($v->errors() as $msg) {
echo ' - ', $msg, "\n";
}
}
Output:
validation failed:
- Email must be a valid email
- Password is too short
The name passes both its rules. The email is present but lacks an @ and a ., so it fails email with a readable message. The password is present but only five characters, failing min:8 and bailing before confirmed is checked -- which is why the confirmation mismatch is not also reported. The result is two clear, per-field messages a form can display beside the offending inputs, precisely what Laravel's form-request validation produces.
The design flaw is that bailing on the password at min:8 hides the confirmation mismatch, so the user fixes the length, resubmits, and only then discovers the passwords do not match -- a second round trip that a non-bailing design would have avoided. Bailing trades completeness for tidiness, and here the trade is arguably wrong: length and confirmation are independent problems the user could fix at once if both were reported. The deeper issue is that "bail" is applied uniformly rather than thoughtfully; the right policy is often per-rule, bailing only when a later rule's result would be meaningless given the earlier failure. Checking min after required failed is meaningless, so bail there; but checking confirmed after min failed is perfectly meaningful, so it should still run. A validator that bails indiscriminately produces cleaner output at the cost of extra user round trips, and choosing that default without considering each field's rules is a usability flaw hiding inside a correctness-looking feature.
Common Mistakes
- Trusting client-side validation. JavaScript checks are trivially bypassed. Always re-validate on the server, treating the browser's checks as convenience only.
- Validating in scattered
ifstatements. Ad hoc checks throughout a controller are easy to miss and hard to reuse. Centralise rules in a validator or form request.
- Using validated-away data anyway. Reading
$_POSTdirectly after validating a separate copy defeats the point. Act only on the validated data.
- Forgetting to check for presence before format. Applying an
emailrule to a missing field can error or mislead. Orderrequiredfirst, and bail when it fails.
- Reporting one error at a time. Making the user fix and resubmit repeatedly is poor UX. Collect all independent failures and show them together.
- Bailing indiscriminately. Stopping at the first failure can hide independent problems the user could fix at once. Bail only when a later rule would be meaningless.
- Weak custom rules. A hand-written email check like "contains @" accepts
a@. Use a robust, well-tested rule rather than a naive substring test.
- Leaking why validation failed for security fields. Telling an attacker exactly which part of a login failed can aid them. For auth, prefer a generic message.
- Not validating types and ranges. Accepting any string for a numeric or enumerated field invites bad data. Validate type, range, and allowed set, not just presence.
Best Practices
- Run all meaningful validation on the server, since it is the only checkpoint a user cannot bypass.
- Declare rules per field in one place -- a validator or form request -- so validation is consistent and reusable.
- Act only on validated data, never reaching back to the raw request after validating a copy.
- Order rules so presence is checked first, and bail on a field only when a later rule would be meaningless without the earlier one.
- Collect independent failures and present them together, so a user can fix everything in one pass.
- Use robust, well-tested rules for formats like email rather than naive substring checks.
- Validate type, range, and allowed set -- not merely presence -- so malformed values never reach your logic.
- Give generic messages for security-sensitive validation such as login, avoiding hints that help an attacker.
Practice Exercises
- Build a validator that applies pipe-separated rules (
required,email,min:N) from a rules array to a data array, and print the per-field failures for an invalid submission.
- Add a passing case with valid data and confirm the validator reports success with zero errors.
- Implement bailing so a field stops at its first failure, and demonstrate that an empty required field reports only
required, not alsomin.
- Extend the validator with a
confirmedrule and human-readable messages, validate a registration form with a length failure and a confirmation mismatch, and discuss which errors should be shown together.