Validation framework lets you configure, rather than code, your validation logic.
composer require abdelrhmansaid/validator
composer test
After registering the rules that you want to use, you can use the validator like this:
use Validator\Validator;
/* Instantiate a new validator */
$validator = new Validator($email);
/* Or you can use the static method init */
$validator = Validator::init($email);
/* Apply your rules */
$validator->email()->required()->max(255);
if (!$validator->validate()) {
return $validator; // validation result in JSON format
}
Also, you can validate multiple values at once:
$errors = Validator::initMultiple($_POST, [
'email' => 'email',
'password' => 'required|min:6|max:255'
]);
if (count($errors)) {
// do something
}
Note that multiple validations return an array of failures rather than a Validator instance.
The validator came without any registered rules by default. You can add them by using the Validator::addRule()
method.
use Validator\Rules\RequiredRule;
Validator::addRule(RequiredRule::class);
Here's a list of pre-defined rules:
Alpha
=> Check if the value is alphabeticBetween
=> Check if the value is between two valuesContains
=> Check if the value contains another valueDoesntContain
=> Check if the value doesn't contain another valueEach
=> Check if each value is validEqual
=> Check if the value is equal to another valueEmail
=> Check if the value is a valid emailIsDate
=> Check if the value is a valid dateMax
=> Check if the value is less than or equal to another valueMin
=> Check if the value is greater than or equal to another valuePattern
=> Check if the value matches a regular expressionRequired
=> Check if the value is not emptyTypeOf
=> Check if the value is a type of certain type
You can submit a pull request to add a new rule.
If you have a specific rule you want to use, you can create a class that extends Validator\AbstractRule
and register it.
class CustomRule extends AbstractRule
{
protected string $message = '...';
public function getName(): string
{
// name will be used to call the rule
}
public function validate(mixed $value, mixed ...$params): bool
{
// validation logic
}
}
If you want to customize the error messages, you can use the Validator::setMessages()
method.
Validator::setMessages([
'required' => 'The value is required.',
'email' => 'The value is not a valid email.'
'max' => 'The value should be less than or equal to {0}.',
]);
Note that you can pass parameters to the message using {x}
placeholders where x
is the index of the parameter.
That's it. Enjoy 👌!