mirror of
https://github.com/Respect/Validation.git
synced 2026-03-17 07:45:45 +01:00
The `setName()` method can be confusing, as it can be tricky for someone to determine which chain is being named. Using the `Named` rule makes this much more explicit and adds a little bit of verbosity. For users, this will be a significant change, but there are easy ways to update this code in their projects, so I’m not overly concerned about it. Another benefit of this change is that it makes the `Validator` much simpler, as it no longer needs to track the name.
2.4 KiB
2.4 KiB
KeyExists
KeyExists(int|string $key)
Validates if the given key exists in an array.
v::keyExists('name')->isValid(['name' => 'The Respect Panda']); // true
v::keyExists('name')->isValid(['email' => 'therespectpanda@gmail.com']); // false
v::keyExists(0)->isValid(['a', 'b', 'c']); // true
v::keyExists(4)->isValid(['a', 'b', 'c']); // false
v::keyExists('username')->isValid(new ArrayObject(['username' => 'therespectpanda'])); // true
v::keyExists(5)->isValid(new ArrayObject(['a', 'b', 'c'])); // false
Notes
- To validate an array against a given rule if the key exists, use KeyOptional instead.
- To validate an array against a given rule requiring the key to exist, use Key instead.
Templates
KeyExists::TEMPLATE_STANDARD
| Mode | Template |
|---|---|
default |
{{subject}} must be present |
inverted |
{{subject}} must not be present |
Template placeholders
| Placeholder | Description |
|---|---|
subject |
The validated input or the custom validator name (if specified). |
Caveats
KeyExists defines the given $key as the path, and because it is a standalone rule without children, it's not possible to display a fully custom name with it.
When no custom name is set, the path is displayed as {{name}}. When a custom name is set, the validation engine prepends the path to the custom name:
v::keyExists('foo')->assert([]);
// Message: `.foo` must be present
v::named(v::keyExists('foo'), 'Custom name')->assert([]);
// Message: `.foo` (<- Custom name) must be present
If you want to display only a custom name while checking if a key exists, use Key with AlwaysValid:
v::key('foo', v::named(v::alwaysValid(), 'Custom name')->assert([]);
// Message: Custom name must be present
Categorization
- Arrays
- Structures
Changelog
| Version | Description |
|---|---|
| 3.0.0 | Created from Key |
See also: