php 59 lines · 8 steps

How a password strength validator works in PHP

A single method runs a password through a table of rules and returns a structured pass/fail report.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5class PasswordStrengthValidator
6{
7 private const MIN_LENGTH = 12;
8 
9 private const COMMON_PASSWORDS = [
10 'password', 'qwerty', '123456', 'letmein', 'admin', 'welcome',
11 ];
12 
13 public function evaluate(string $password): array
14 {
15 $normalized = strtolower(trim($password));
16 
17 $rules = [
18 'min_length' => [
19 'passed' => mb_strlen($password) >= self::MIN_LENGTH,
20 'message' => sprintf('Must be at least %d characters long.', self::MIN_LENGTH),
21 ],
22 'uppercase' => [
23 'passed' => (bool) preg_match('/[A-Z]/', $password),
24 'message' => 'Must contain at least one uppercase letter.',
25 ],
26 'lowercase' => [
27 'passed' => (bool) preg_match('/[a-z]/', $password),
28 'message' => 'Must contain at least one lowercase letter.',
29 ],
30 'digit' => [
31 'passed' => (bool) preg_match('/\d/', $password),
32 'message' => 'Must contain at least one number.',
33 ],
34 'symbol' => [
35 'passed' => (bool) preg_match('/[^A-Za-z0-9]/', $password),
36 'message' => 'Must contain at least one special character.',
37 ],
38 'no_whitespace' => [
39 'passed' => ! preg_match('/\s/', $password),
40 'message' => 'Must not contain spaces.',
41 ],
42 'not_common' => [
43 'passed' => ! in_array($normalized, self::COMMON_PASSWORDS, true),
44 'message' => 'Must not be a commonly used password.',
45 ],
46 ];
47 
48 $failed = array_filter($rules, static fn (array $rule): bool => ! $rule['passed']);
49 
50 return [
51 'valid' => $failed === [],
52 'rules' => $rules,
53 'errors' => array_values(array_map(
54 static fn (array $rule): string => $rule['message'],
55 $failed
56 )),
57 ];
58 }
59}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Expressing checks as a data table keeps each rule self-documenting and easy to extend.
  2. 2Returning both the full rule set and a flat error list lets callers choose how much detail to show.
  3. 3Normalizing input once up front avoids repeating case and whitespace handling across checks.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a password strength validator works in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code