Copy
<?php
// Reusable validator helper
function validate(array $data, array $rules): array
{
$errors = [];
foreach ($rules as $field => $rule) {
$value = trim($data[$field] ?? '');
foreach (explode('|', $rule) as $r) {
[$type, $param] = array_pad(explode(':', $r, 2), 2, null);
match ($type) {
'required' => $value === '' ? $errors[$field][] = "$field is required" : null,
'min' => strlen($value) < $param ? $errors[$field][] = "$field min $param chars" : null,
'max' => strlen($value) > $param ? $errors[$field][] = "$field max $param chars" : null,
'email' => !filter_var($value, FILTER_VALIDATE_EMAIL) ? $errors[$field][] = "$field must be valid email" : null,
'numeric' => !is_numeric($value) ? $errors[$field][] = "$field must be numeric" : null,
default => null,
};
}
}
return $errors;
}
// Usage
$rules = [
'name' => 'required|min:2|max:100',
'email' => 'required|email',
'age' => 'required|numeric',
];
$errors = validate($_POST, $rules);
if (empty($errors)) {
// Process, then redirect (PRG pattern)
header('Location: /success.php');
exit;
}