50 lines
2.0 KiB
PHP
50 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* Simple Data Validator
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
final class Validator
|
|
{
|
|
public static function validate(array $data, array $rules): array
|
|
{
|
|
$errors = [];
|
|
foreach ($rules as $field => $rule) {
|
|
$value = $data[$field] ?? null;
|
|
|
|
if (str_contains($rule, 'required') && (empty($value) && $value !== '0')) {
|
|
$errors[$field] = "The {$field} field is required.";
|
|
continue; // Skip further rules if required field is missing
|
|
}
|
|
|
|
if (str_contains($rule, 'email') && !empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
|
$errors[$field] = "The {$field} must be a valid email address.";
|
|
}
|
|
|
|
// Password strength: min 8 chars, at least 1 uppercase, 1 lowercase, 1 digit
|
|
if (str_contains($rule, 'strong_password') && !empty($value)) {
|
|
if (strlen($value) < 8) {
|
|
$errors[$field] = 'كلمة المرور يجب أن تكون 8 أحرف على الأقل.';
|
|
} elseif (!preg_match('/[A-Z]/', $value)) {
|
|
$errors[$field] = 'كلمة المرور يجب أن تحتوي على حرف كبير واحد على الأقل.';
|
|
} elseif (!preg_match('/[a-z]/', $value)) {
|
|
$errors[$field] = 'كلمة المرور يجب أن تحتوي على حرف صغير واحد على الأقل.';
|
|
} elseif (!preg_match('/[0-9]/', $value)) {
|
|
$errors[$field] = 'كلمة المرور يجب أن تحتوي على رقم واحد على الأقل.';
|
|
}
|
|
}
|
|
|
|
// Generic min length: min:8
|
|
if (preg_match('/min:(\d+)/', $rule, $m) && !empty($value)) {
|
|
if (mb_strlen($value) < (int)$m[1]) {
|
|
$errors[$field] = "The {$field} must be at least {$m[1]} characters.";
|
|
}
|
|
}
|
|
}
|
|
return $errors;
|
|
}
|
|
}
|