Validation
The Ecommerce\Validation\Validator class provides a robust way to validate data against a set of rules. It supports nested data structures, wildcards, and custom validation closures.
Basic Usage
Validate an array of data.
Create Validator
Make a new validator instance.
Description:
The make() method creates a new validator instance with the data and rules provided.
Method Signature:
public static function make(array $data, array $rules): Validator
Parameters:
$data- The data array to validate.$rules- An associative array of validation rules.
Examples:
use Ecommerce\Validation\Validator;
$data = ['email' => 'test@example.com', 'age' => 25];
$validator = Validator::make($data, [
'email' => 'required|email',
'age' => 'required|int|min:18'
]);
Run Validation
Execute the validation rules.
Description:
The validate() method runs the validation. If validation fails, it throws a ValidationException. If successful, it returns true.
Method Signature:
public function validate(): bool
Examples:
try {
$validator->validate();
// Validation passed
} catch (ValidationException $e) {
$errors = $e->errors();
}
Get Validated Data
Retrieve only the valid data.
Description:
The validated() method returns an array containing only the data attributes that were specified in the validation rules.
Method Signature:
public function validated(): array
Examples:
$validator->validate();
$safeData = $validator->validated();
Check Status
Manually check validation status without throwing exceptions.
Check Validity
Determine if the data passed validation.
Description:
The is_valid() method runs validation and returns a boolean true if passed, false otherwise.
Method Signature:
public function is_valid(): bool
Examples:
if ($validator->is_valid()) {
// Proceed
}
Check Failure
Determine if the validation failed.
Description:
The is_failed() method returns true if any rule failed.
Method Signature:
public function is_failed(): bool
Examples:
if ($validator->is_failed()) {
return $validator->get_errors();
}
Get Errors
Retrieve validation errors.
Description:
The get_errors() method returns an array of error messages keyed by the field name.
Method Signature:
public function get_errors(): ?array
Examples:
$errors = $validator->get_errors();
// ['email' => ['The email field is required.']]
Advanced Usage
Working with nested data and conditional rules.
Nested & Wildcard Rules
Validate nested arrays using dot notation.
Description:
You can validate nested data structures using dot notation. The * wildcard can be used to validate arrays of items.
Examples:
$validator = Validator::make($request->all(), [
'items.*.product_id' => 'required|int',
'items.*.quantity' => 'required|int|min:1',
'shipping.address.city' => 'required|string'
]);
Conditional Validation
Apply rules only if a condition is met.
Description:
The apply_if() method allows adding rules dynamically based on the data.
Method Signature:
public function apply_if(string|array $field, string $rules, callable $callback): Validator
Examples:
$validator->apply_if('tax_id', 'required|string', function ($data) {
return $data['is_business_customer'] === true;
});
Available Validation Rules
Here is a list of all available validation rules and their function:
| Rule | Description |
|---|---|
required | The field under validation must be present in the input data and not empty. A field is considered "empty" if it is null or an empty string. |
string | The field under validation must be a string. |
array | The field under validation must be a PHP array. |
object | The field under validation must be a PHP object. |
boolean | The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0". |
integer | The field under validation must be an integer. |
number | The field under validation must be numeric. |
float | The field under validation must be an float. |
email | The field under validation must be formatted as an email address. |
email_unique | The field must be a valid email and must not exist in the users table. |
unique:table,column,except,idColumn | The field under validation must not exist within the given database table. |
url | The field under validation must be a valid URL. |
exists:table,column | The field under validation must exist on a given database table. |
min:value | The field under validation must have a minimum value. Strings, numerics, and arrays are evaluated in the same fashion as the size rule. |
max:value | The field under validation must be less than or equal to a maximum value. Strings, numerics, and arrays are evaluated in the same fashion as the size rule. |
in:foo,bar,... | The field under validation must be included in the given list of values. |
not_in:foo,bar,... | The field under validation must not be included in the given list of values. |
regex:pattern | The field under validation must match the given regular expression. |
sanitize:filter | Sanitizes the input using the specified filter (e.g., text, email, url, trim). |
same_as:field | The given field must match the field under validation. |
nullable | The field under validation may be null. |
date | The field under validation must be a valid, non-relative date. |
datetime | The field under validation must be a valid datetime. |
date_format:format | The field under validation must match the given format. You should use either date or date_format when validating a field, not both. |
is_valid_image_id | The field under validation must be a valid WordPress image attachment ID. |
required_if:anotherfield,value | The field under validation is required if the anotherfield field is equal to any value. |
prohibited_if:anotherfield,value | The field under validation must be missing or empty if the anotherfield field is equal to any value. |
required_if_exists:anotherfield | The field under validation is required if the anotherfield field is present. |
user_exists | The field under validation must be a valid user ID. |
after:date | The field under validation must be a value after a given date. The dates will be passed into the PHP strtotime function. |
gt:field | The field under validation must be greater than the given field. The two fields must be of the same type. |
gte:field | The field under validation must be greater than or equal to the given field. The two fields must be of the same type. |
lt:field | The field under validation must be less than the given field. The two fields must be of the same type. |
lte:field | The field under validation must be less than or equal to the given field. The two fields must be of the same type. |
tribute_fields | Validates tribute fields based on campaign settings and notification preferences (e.g. checks recipient name, email/address based on notification type). |