Validation
Single Value
To validate a single value, use the Validator::validate()
. The method takes two arguments:
- The value to validate: This is a data you want to check.
- A rule object: This object represents the validation rule you want to apply. The library provides various built-in rules, and you can also create custom rules.
Arrays
The library can validate arrays of data. Here’s how you would do it:
- Create an array of data: This array will contain the key-value pairs you want to validate.
- Create an array of rules: The keys of this array should match the keys of your data array. The values are rule objects that define the validation criteria for each field.
- Pass data and rules to the
validate()
method: The validator will check each value in the data array against its corresponding rule.
Objects
Instances of stdClass
You can apply validation rules to objects as well. When working with stdClass
instances, the process is similar to
validating arrays:
- Create an instance of
stdClass
: This object will hold the properties you want to validate. - Create an array of rules: The keys of your rules array should correspond to the property names within your stdClass object. The values will be rule objects.
- Pass the object and rules to the
validate()
method: The validator will treat the properties of your object as individual values and apply the corresponding rules.
Data Transfer Objects
Data Transfer Objects (DTOs) are simple objects designed to carry data between different parts of your application. Your validation library can streamline the process of ensuring that DTOs contain valid data. Here are two common approaches:
Using an array of rules
- Similar to validating stdClass objects, create an array of rules where the keys match the names of the properties on your DTO.
- Pass the DTO and the rules array to the
validate()
method.
Using rule attributes
- Define rule attributes on the DTO properties.
- Pass the DTO to the
validate()
method (the validator would need to be able to read and interpret these attributes).
Collections
The library provides seamless ways to validate collections.
Arrays of Values with EachX
Use the EachX
instruction to apply the same validation rule to every element within an array.
Example:
Nested Arrays or Objects
Create nested validation rule arrays to define rules for specific elements within arrays or objects. The keys in your rules array should match the keys of the data being validated.
Example: