mirror of
https://github.com/Respect/Validation.git
synced 2024-06-03 06:12:17 +02:00
d36572cc25
Currently, the Property rule has a third parameter that allows the validation of the wrapped rule to be optional, meaning that the validation will only happen if the property exists. That parameter makes the rule harder to understand at times. I'm splitting the Property rule into Property, PropertyExists, and PropertyOptional. That way, it becomes apparent when someone wants only to validate whether a property exists or if they will validate the value of the property only when it exists. I deliberately didn't create an abstract class because those rules are different enough not to have an abstraction. In fact, I can see myself deleting the AbstractRelated after I refactor the KeyNested rule. Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
1.8 KiB
1.8 KiB
KeyOptional
KeyOptional(int|string $key, Validatable $rule)
Validates the value of an array against a given rule when the key exists.
v::keyOptional('name', v::stringType())->validate([]); // true
v::keyOptional('name', v::stringType())->validate(['name' => 'The Respect Panda']); // true
v::keyOptional('email', v::email())->validate([]); // true
v::keyOptional('email', v::email())->validate(['email' => 'therespectpanda@gmail.com']); // true
v::keyOptional('age', v::intVal())->validate(['age' => 'Twenty-Five']); // false
The name of this validator is automatically set to the key name.
v::keyOptional('age', v::intVal())->assert(['age' => 'Twenty-Five']);
// message: age must be an integer number
Note
This rule will pass for anything that is not an array because it will always pass when it doesn't find a key. If you want to ensure the input is an array, use ArrayType with it.
v::arrayType()->keyOptional('phone', v::phone())->assert('This is not an array');
// message: "This is not an array" must be of type array
Below are some other rules that are tightly related to KeyOptional
:
- To validate if a key exists, use KeyExists instead.
- To validate an array against a given rule requiring the key to exist, use Key instead.
Categorization
- Arrays
- Structures
Changelog
Version | Description |
---|---|
3.0.0 | Created from Key |
See also: