php
53 lines · 8 steps
Validating registration input with filter_var
A validator uses PHP's filter_var to check, sanitize, and normalize form fields, collecting errors before returning clean data.
Explained by
highlit
1<?php
2
3declare(strict_types=1);
4
5final class RegistrationValidator
6{
7 private array $errors = [];
8
9 public function validate(array $input): ?array
10 {
11 $email = filter_var(trim($input['email'] ?? ''), FILTER_VALIDATE_EMAIL);
12 if ($email === false) {
13 $this->errors['email'] = 'A valid email address is required.';
14 }
15
16 $age = filter_var($input['age'] ?? null, FILTER_VALIDATE_INT, [
17 'options' => ['min_range' => 18, 'max_range' => 120],
18 ]);
19 if ($age === false) {
20 $this->errors['age'] = 'Age must be a whole number between 18 and 120.';
21 }
22
23 $website = filter_var($input['website'] ?? '', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED);
24 if (!empty($input['website']) && $website === false) {
25 $this->errors['website'] = 'The website URL is malformed.';
26 }
27
28 $bio = filter_var(
29 $input['bio'] ?? '',
30 FILTER_SANITIZE_FULL_SPECIAL_CHARS,
31 FILTER_FLAG_NO_ENCODE_QUOTES
32 );
33
34 $newsletter = filter_var($input['newsletter'] ?? false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
35
36 if ($this->errors !== []) {
37 return null;
38 }
39
40 return [
41 'email' => $email,
42 'age' => $age,
43 'website' => $website ?: null,
44 'bio' => $bio,
45 'newsletter' => (bool) $newsletter,
46 ];
47 }
48
49 public function errors(): array
50 {
51 return $this->errors;
52 }
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1filter_var handles validation, sanitization, and normalization in one well-typed call with configurable flags.
- 2Accumulating errors into a map lets you report every problem at once instead of failing on the first.
- 3Returning either clean data or null gives callers a clear success/failure contract.
Related explainers
php
<?php namespace App\Http\Controllers;
Building a filtered product index in Laravel
query-builder
validation
conditional-queries
Intermediate
9 steps
rust
use axum::{ body::Bytes, extract::State, http::StatusCode,
Handling raw byte uploads in Axum
extractors
shared-state
request-limits
Intermediate
7 steps
php
<?php namespace App\Models\Scopes;
How a tenant global scope works in Laravel
multi-tenancy
global-scope
query-builder
Intermediate
5 steps
javascript
const RETRIABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]); function sleep(ms, signal) { return new Promise((resolve, reject) => {
Retrying fetch with exponential backoff
retry
exponential-backoff
abort-signal
Advanced
8 steps
rust
use axum::{ extract::{Query, State}, http::StatusCode, Json,
Paginated, filtered product listing in Axum
pagination
query-parameters
sql-filtering
Intermediate
8 steps
typescript
type EventMap = Record<string, unknown[]>; type Listener<Args extends unknown[]> = (...args: Args) => void;
A type-safe event emitter in TypeScript
generics
mapped-types
event-emitter
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-registration-input-with-filter_var-explained-php-7207/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.