Displaying Validation Errors
When validation fails, Trongate stores errors in $_SESSION['form_submission_errors'] and provides three simple ways to display them.
The Three Display Methods
| Method | How to Use | Best For |
|---|---|---|
| General Errors | validation_errors() |
Simple forms, login pages, admin panels |
| Inline Errors | validation_errors('field_name') |
Long forms, multi-step forms, better UX |
| JSON Errors | validation_errors(422) |
API endpoints, AJAX forms, mobile apps |
Method 1: General Errors (Display All)
Use with no arguments to display all validation errors at once, typically at the top of your form.
This approach is ideal for short forms where a single error summary is sufficient.
Customising Output
- Wrap each error:
- Set global defaults:
- Wrap the full block:
Method 2: Inline Errors (Field-Specific)
Pass a field name to display errors next to the relevant input. This provides a more precise and user-friendly experience.
This method is ideal for longer or more complex forms where users benefit from seeing exactly where problems occur.
Method 3: JSON Errors (APIs and AJAX)
Pass an HTTP status code (400–499) to return validation errors as JSON and immediately terminate execution.
Example JSON response:
Important: The JSON method terminates execution using exit(). No code after validation_errors(422) will run.
Automatic Error Highlighting
Add the highlight-errors class to your form to automatically highlight fields that failed validation.
When validation errors exist, injects JavaScript that applies the form-field-validation-error class to affected fields.
Choosing the Right Approach
- Simple forms: Use general errors
- Complex forms: Use inline errors
- APIs: Use JSON responses
Best Practice: Choose one primary display method per form. Mixing approaches can lead to a confusing user experience.
Session Behaviour (Advanced)
Good to know: Validation errors are automatically cleared from the session after they are displayed.
In most cases, you don’t need to think about this - but for completeness:
validation_errors()displays all errors and clears themvalidation_errors('field')displays errors for one field and clears only that field’s errorsvalidation_errors(422)returns JSON, clears all errors, and terminates execution$this->validation->run()clears previous errors before running validation again
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.