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

Walkthrough

Space play step click any line
Three takeaways
  1. 1filter_var handles validation, sanitization, and normalization in one well-typed call with configurable flags.
  2. 2Accumulating errors into a map lets you report every problem at once instead of failing on the first.
  3. 3Returning either clean data or null gives callers a clear success/failure contract.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating registration input with filter_var — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code