Skip to main content

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:

RuleDescription
requiredThe 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.
stringThe field under validation must be a string.
arrayThe field under validation must be a PHP array.
objectThe field under validation must be a PHP object.
booleanThe field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".
integerThe field under validation must be an integer.
numberThe field under validation must be numeric.
floatThe field under validation must be an float.
emailThe field under validation must be formatted as an email address.
email_uniqueThe field must be a valid email and must not exist in the users table.
unique:table,column,except,idColumnThe field under validation must not exist within the given database table.
urlThe field under validation must be a valid URL.
exists:table,columnThe field under validation must exist on a given database table.
min:valueThe field under validation must have a minimum value. Strings, numerics, and arrays are evaluated in the same fashion as the size rule.
max:valueThe 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:patternThe field under validation must match the given regular expression.
sanitize:filterSanitizes the input using the specified filter (e.g., text, email, url, trim).
same_as:fieldThe given field must match the field under validation.
nullableThe field under validation may be null.
dateThe field under validation must be a valid, non-relative date.
datetimeThe field under validation must be a valid datetime.
date_format:formatThe 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_idThe field under validation must be a valid WordPress image attachment ID.
required_if:anotherfield,valueThe field under validation is required if the anotherfield field is equal to any value.
prohibited_if:anotherfield,valueThe field under validation must be missing or empty if the anotherfield field is equal to any value.
required_if_exists:anotherfieldThe field under validation is required if the anotherfield field is present.
user_existsThe field under validation must be a valid user ID.
after:dateThe field under validation must be a value after a given date. The dates will be passed into the PHP strtotime function.
gt:fieldThe field under validation must be greater than the given field. The two fields must be of the same type.
gte:fieldThe field under validation must be greater than or equal to the given field. The two fields must be of the same type.
lt:fieldThe field under validation must be less than the given field. The two fields must be of the same type.
lte:fieldThe field under validation must be less than or equal to the given field. The two fields must be of the same type.
tribute_fieldsValidates tribute fields based on campaign settings and notification preferences (e.g. checks recipient name, email/address based on notification type).