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
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 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.