Version 3.0 will include a few crucial deprecations. This commit adds some soft deprecations to warn users about these changes. Some of the biggest changes are: * The method `validate()` will be renamed to `isValid()`. * The method `validate()` will be repurposed to return an object with failures. * It won't be possible to handle rules directly; users will need to use the `Validator` class to validate with any rule. There will some more changes, but those are some of the most important ones, and are the ones that are easy to deprecate right now.
2.1 KiB
KeyValue
keyValue(string $comparedKey, string $ruleName, string $baseKey)
Performs validation of $comparedKey using the rule named on $ruleName with
$baseKey as base.
Sometimes, when validating arrays, the validation of a key value depends on another key value and that may cause some ugly code since you need the input before the validation, making some checking manually:
v::key('password', v::notEmpty())->isValid($_POST);
v::key('password_confirmation', v::equals($_POST['password'] ?? null))->isValid($_POST);
The problem with the above code is because you do not know if password is a
valid key, so you must check it manually before performing the validation on
password_confirmation.
The keyValue() rule makes this job easier by creating a rule named on
$ruleName passing $baseKey as the first argument of this rule, see an example:
v::keyValue('password_confirmation', 'equals', 'password')->isValid($_POST);
The above code will result on true if $_POST['password_confirmation'] is
equals to $_POST['password'], it's the same of:
See another example:
v::keyValue('state', 'subdivisionCode', 'country')->isValid($_POST);
The above code will result on true if $_POST['state'] is a
subdivision code of $_POST['country']:
This rule will invalidate the input if $comparedKey or $baseKey don't exist,
or if the rule named on $ruleName could not be created (or don't exist).
When using assert() or check() methods and the rule do not pass, it overwrites
all values in the validation exceptions with $baseKey and $comparedKey.
try {
v::keyValue('password_confirmation', 'equals', 'password')->check($_POST);
} catch (ValidationException $exception) {
// ..
}
The above code may generate the message:
password_confirmation must equal "password"
Categorization
- Arrays
- Nesting
Changelog
| Version | Description |
|---|---|
| 1.0.0 | Created |
See also: