Violations
violations() returns a list of EugeneErg\Assert\Violation, and ValidationException::$violations holds the same list:
php
$violation = Assert::between(Assert::ref('qty'), 1, 10)->violations(['qty' => 11])[0];
$violation->code; // "between"
$violation->path; // ["qty"]
$violation->message; // "qty must be greater than or equal to 1 and less than or equal to 10"
$violation->parameters; // ["value" => 11, "from" => 1, "to" => 10, "fromInclusive" => true, "toInclusive" => true]
$violation->negated; // falsepathis where the subject lies in the data: string and int keys, empty for the root or a literal.parametershold the value of every operand under its name (value,limit,from,to,expected,choices,class,pattern) and the options of the rule (strict,allowString,type, ...).negatedistruewhen the rule failed undernot().
Codes
| Code | Means |
|---|---|
the rule's name: lessThan, between, type, exists, in, ... | the rule did not hold |
invalid | an operand cannot be checked by this rule at all: wrong type, unknown class, broken pattern. parameters has the value and the rule it was for. Never negated |
any | no alternative held; alternatives lists the violations of each alternative |
some | the iterable had no elements, so none could match |
php
$violation = Assert::lessThan(Assert::ref('qty'), 10)->violations(['qty' => '5'])[0];
$violation->code; // "invalid"
$violation->parameters; // ["value" => "5", "rule" => "lessThan"]The exception
assert() throws ValidationException with all the violations. Its message is their messages, one per line, unless you pass your own:
php
try {
$rule->assert($data, 'The order is invalid.');
} catch (ValidationException $exception) {
$exception->getMessage(); // "The order is invalid."
$exception->violations; // non-empty-list<Violation>
}An API response
The path and code are enough to build the usual error format:
php
$errors = array_map(
static fn (Violation $violation): array => [
'field' => implode('.', $violation->path),
'code' => $violation->code,
'message' => $violation->message,
],
$rule->violations($request->toArray()),
);Messages in other languages
The messages are English. For other languages, build the text from code and parameters, for example with ICU MessageFormat templates keyed by code. The ICU i18n translator can machine-translate such templates into every language your app supports.