Validation Patterns
Normalized Codes
Normalize a code before validating its shape.
normalized-code
Validation often works better after normalization. This example trims and uppercases a code before checking its expected prefix and length.
Normalized Codes
normalized_code.php
Replay: real traced execution (multi-file project)
<?php
$code = "ab12";
$normalized = strtoupper(trim($code));
$hasPrefix = str_starts_with($normalized, "AB");
$hasLength = strlen($normalized) === 4;
$status = $hasPrefix && $hasLength ? "valid" : "invalid";
echo "code=" . $code . "\n";
echo "normalized=" . $normalized . "\n";
echo "status=" . $status . "\n";
<?php
$code = "xy99";
$normalized = strtoupper(trim($code));
$hasPrefix = str_starts_with($normalized, "AB");
$hasLength = strlen($normalized) === 4;
$status = $hasPrefix && $hasLength ? "valid" : "invalid";
echo "code=" . $code . "\n";
echo "normalized=" . $normalized . "\n";
echo "status=" . $status . "\n";
<?php
$code = "bad";
$normalized = strtoupper(trim($code));
$hasPrefix = str_starts_with($normalized, "AB");
$hasLength = strlen($normalized) === 4;
$status = $hasPrefix && $hasLength ? "valid" : "invalid";
echo "code=" . $code . "\n";
echo "normalized=" . $normalized . "\n";
echo "status=" . $status . "\n";
$code ← ab12, $normalized ← AB12, $hasPrefix ← 1, $hasLength ← 1
1<?php2$code→ ab12 = "ab12"; //@code="xy99", "bad"3$normalized→ AB12 = strtoupper(trim($codeab12));4$hasPrefix→ 1 = str_starts_with($normalizedAB12, "AB");5$hasLength→ 1 = strlen($normalizedAB12) === 4;6$status→ valid = $hasPrefix1 && $hasLength1 ? "valid" : "invalid";78echo "code=" . $codeab12 . "\n";9echo "normalized=" . $normalizedAB12 . "\n";10echo "status=" . $statusvalid . "\n";outputcode=ab12 normalized=AB12 status=valid
$code ← xy99, $normalized ← XY99, $hasPrefix ← (empty), $hasLength ← 1
1<?php2$code→ xy99 = "xy99";3$normalized→ XY99 = strtoupper(trim($codexy99));4$hasPrefix→ (empty) = str_starts_with($normalizedXY99, "AB");5$hasLength→ 1 = strlen($normalizedXY99) === 4;6$status→ invalid = $hasPrefix(empty) && $hasLength1 ? "valid" : "invalid";78echo "code=" . $codexy99 . "\n";9echo "normalized=" . $normalizedXY99 . "\n";10echo "status=" . $statusinvalid . "\n";outputcode=xy99 normalized=XY99 status=invalid
$code ← bad, $normalized ← BAD, $hasPrefix ← (empty), $hasLength ← (empty)
1<?php2$code→ bad = "bad";3$normalized→ BAD = strtoupper(trim($codebad));4$hasPrefix→ (empty) = str_starts_with($normalizedBAD, "AB");5$hasLength→ (empty) = strlen($normalizedBAD) === 4;6$status→ invalid = $hasPrefix(empty) && $hasLength(empty) ? "valid" : "invalid";78echo "code=" . $codebad . "\n";9echo "normalized=" . $normalizedBAD . "\n";10echo "status=" . $statusinvalid . "\n";outputcode=bad normalized=BAD status=invalid