respect-validation/docs/rules/Property.md
Henrique Moody 7cec227520
Create "Attribute" rule
With this change, any rule can be used as a PHP attribute. I have wanted
to implement this feature for a while, as it allows you to bind the
validation to a specific property and just validate the object
afterwards.
2024-12-13 03:49:29 +01:00

2.4 KiB

Property

  • Property(string $propertyName, Rule $rule)

Validates an object property against a given rule.

$object = new stdClass;
$object->name = 'The Respect Panda';
$object->email = 'therespectpanda@gmail.com';

v::property('name', v::equals('The Respect Panda'))->isValid($object); // true

v::property('email', v::email())->isValid($object); // true

v::property('email', v::email()->endsWith('@example.com'))->assert($object); // false

You can also use Property to validate nested objects:

$object->address = new stdClass();
$object->address->postalCode = '1017 BS';

v::property(
    'address',
    v::property('postalCode', v::postalCode('NL'))
)->isValid($object); // true

The name of this validator is automatically set to the property name.

v::property('website', v::url())->assert($object);
// message: website must be present

v::property('name', v::uppercase())->assert($object);
// message: name must be uppercase

Note

This rule will validate public, private, protected, uninitialised, and static properties.

  • To only validate if a property exists, use PropertyExists instead.
  • To validate a property against a given rule only if the property exists, use PropertyOptional instead.

Templates

Template placeholders

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

Categorization

  • Nesting
  • Objects
  • Structures

Changelog

Version Description
3.0.0 Renamed from Attribute to Property, and split by PropertyExists and PropertyOptional
0.3.9 Created

See also: