Understanding validation errors
When validation fails, there are two layers of information:
- the thrown exception
- the validator’s
ErrorList
The exception tells us that validation failed. The ErrorList tells us which fields failed and what message to show.
The thrown exception
Validator::validate() throws a ValidationException when one or more fields are invalid.
The message is intentionally broad:
There is 1 invalid fieldThere are 2 invalid fields
That message is useful for logging or for a general summary, but not for field-by-field display.
The ErrorList
The detailed information is available through:
$validator->getLastErrorList()
The returned object is iterable and countable.
catch(ValidationException) {
$errorList = $validator->getLastErrorList();
foreach($errorList as $name => $message) {
// ...
}
}
Keys and values of getLastErrorList()
During iteration:
- the key is the field name
- the value is the message to show for that field
Example:
foreach($validator->getLastErrorList() as $name => $message) {
echo "$name => $message\n";
}
Possible output:
password => This field is required; This field's value must contain at least 12 characters
Multiple problems on one field
One field may fail more than one rule.
For example:
<input name="password" minlength="12" required />
If the submitted value is empty, both rules fail:
requiredminlength
The ErrorList combines those messages into one string using ; as a separator.
That means the library gives us one display message per field, even if several rules contributed to it.
Specific exception classes
Internally, the library also tracks more specific exception classes such as:
ValueMissingExceptionPatternMismatchExceptionTypeMismatchExceptionRangeUnderflowExceptionRangeOverflowExceptionStepMismatchExceptionBadInputException
If every invalid field belongs to the same category, the validator throws that specific exception class.
If the invalid fields belong to mixed categories, it throws the broader ValidityStateException.
For most applications, the field-level messages are the part we act on most often. The exception type becomes useful when a higher-level handler needs to distinguish one family of validation problems from another.
Counting invalid fields
The ErrorList count is the number of invalid fields, not the number of individual failed rules.
So if one field fails both required and minlength, it still counts as one invalid field.
A practical pattern
Use the exception to branch the control flow, and use the error list to render the response:
try {
$validator->validate($form, $input);
}
catch(ValidationException) {
foreach($validator->getLastErrorList() as $name => $message) {
// Render field-level errors.
}
return;
}
Now that the error data shape is clear, continue with Displaying error messages or move on to Extending custom rules.