You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.9 KiB
71 lines
1.9 KiB
<?php
|
|
class Validator {
|
|
protected $rules = [];
|
|
|
|
public function rule($field, callable $callback, $message = '') {
|
|
$this->rules[$field][] = [
|
|
'callback' => $callback,
|
|
'message' => $message
|
|
];
|
|
return $this;
|
|
}
|
|
|
|
public function validate(array $data) {
|
|
$errors = [];
|
|
|
|
foreach ($this->rules as $field => $fieldRules) {
|
|
foreach ($fieldRules as $rule) {
|
|
if (!array_key_exists($field, $data) || !call_user_func($rule['callback'], $data[$field])) {
|
|
$errors[$field][] = $rule['message'] ?: "The field {$field} is invalid.";
|
|
}
|
|
}
|
|
}
|
|
|
|
return $errors;
|
|
}
|
|
|
|
public function assert(array $data) {
|
|
$errors = $this->validate($data);
|
|
if (!empty($errors)) {
|
|
throw new ValidationException($errors);
|
|
}
|
|
}
|
|
|
|
// Static helper methods for common validations
|
|
public static function required() {
|
|
return function ($value) {
|
|
return !empty($value);
|
|
};
|
|
}
|
|
|
|
public static function email() {
|
|
return function ($value) {
|
|
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
|
|
};
|
|
}
|
|
|
|
public static function minLength($length) {
|
|
return function ($value) use ($length) {
|
|
return mb_strlen($value) >= $length;
|
|
};
|
|
}
|
|
|
|
public static function maxLength($length) {
|
|
return function ($value) use ($length) {
|
|
return mb_strlen($value) <= $length;
|
|
};
|
|
}
|
|
|
|
public static function regex($pattern) {
|
|
return function ($value) use ($pattern) {
|
|
return preg_match($pattern, $value) === 1;
|
|
};
|
|
}
|
|
|
|
public static function number() {
|
|
return function ($value) {
|
|
return filter_var($value, FILTER_VALIDATE_FLOAT) !== false;
|
|
};
|
|
}
|
|
|
|
} |