respect-validation/docs/rules/KeySet.md
2024-12-09 01:34:50 +01:00

3.1 KiB

KeySet

  • KeySet(KeyRelated $rule, KeyRelated ...$rules)

Validates a keys in a defined structure.

v::keySet(
    v::keyExists('foo'),
    v::keyExists('bar')
)->isValid(['foo' => 'whatever', 'bar' => 'something']); // true

It will validate the keys in the array with the rules passed in the constructor.

v::keySet(
    v::key('foo', v::intVal())
)->isValid(['foo' => 42]); // true

v::keySet(
    v::key('foo', v::intVal())
)->isValid(['foo' => 'string']); // false

Extra keys are not allowed:

v::keySet(
    v::key('foo', v::intVal())
)->isValid(['foo' => 42, 'bar' => 'String']); // false

Missing required keys are not allowed:

v::keySet(
    v::key('foo', v::intVal()),
    v::key('bar', v::stringType()),
    v::key('baz', v::boolType())
)->isValid(['foo' => 42, 'bar' => 'String']); // false

Missing non-required keys are allowed:

v::keySet(
    v::key('foo', v::intVal()),
    v::key('bar', v::stringType()),
    v::keyOptional('baz', v::boolType())
)->isValid(['foo' => 42, 'bar' => 'String']); // true

Alternatively, you can pass a chain of key-related rules to keySet():

v::keySet(
    v::create()
        ->key('foo', v::intVal())
        ->key('bar', v::stringType())
        ->keyOptional('baz', v::boolType())
)->isValid(['foo' => 42, 'bar' => 'String']); // true

It is not possible to negate keySet() rules with not().

The keys' order is not considered in the validation.

Templates

KeySet::TEMPLATE_STANDARD

Mode Template
default {{name}} validation failed
inverted {{name}} validation passed

KeySet::TEMPLATE_BOTH

Mode Template
default {{name}} contains both missing and extra keys
inverted {{name}} contains no missing or extra keys.

KeySet::TEMPLATE_EXTRA_KEYS

Mode Template
default {{name}} contains extra keys
inverted {{name}} contains no extra keys

KeySet::TEMPLATE_MISSING_KEYS

Mode Template
default {{name}} contains missing keys
inverted {{name}} contains no missing keys

Template placeholders

Placeholder Description
name The validated input or the custom validator name (if specified).

Categorization

  • Arrays
  • Nesting
  • Structures

Changelog

Version Description
3.0.0 Requires at least one key-related rule
2.3.0 KeySet is NonNegatable, fixed message with extra keys
1.0.0 Created

See also: