Skip to content

fix: refine FormRequest JSON failure detection#10240

Open
memleakd wants to merge 1 commit into
codeigniter4:4.8from
memleakd:fix/formrequest-json-failure-detection
Open

fix: refine FormRequest JSON failure detection#10240
memleakd wants to merge 1 commit into
codeigniter4:4.8from
memleakd:fix/formrequest-json-failure-detection

Conversation

@memleakd
Copy link
Copy Markdown
Contributor

Description

This PR adjusts the default FormRequest validation failure response so AJAX/XHR requests are not treated as JSON requests automatically.

Currently, the default failedValidation() returns a 422 JSON response when either:

  • the request body is JSON, or
  • the request has X-Requested-With: XMLHttpRequest

The JSON body case makes sense, but the XHR case feels too broad. A lot of modern apps use AJAX-like requests while still expecting HTML in response. HTMX, Turbo, Unpoly, and similar HTML-over-the-wire approaches can submit forms asynchronously, but the response may still be an HTML form, modal, sheet, or page fragment with validation errors. In those cases, receiving JSON validation errors by default is surprising and makes FormRequest harder to use for HTML-first applications.

With this change, the default JSON response is selected only when the client is explicit about JSON:

  • Content-Type: application/json
  • Accept: application/json

Plain AJAX/XHR requests now follow the normal web behavior and redirect back with input and validation errors. If an AJAX client expects JSON, it can send Accept: application/json, while HTML-first apps are not pushed into JSON accidentally.

This keeps the default behavior predictable. Apps that need custom failure responses can still override failedValidation(), just like they can today.

The docs were updated to make this explicit, and the tests cover JSON body, JSON Accept, AJAX-only, AJAX plus JSON Accept, wildcard Accept, and the controller integration path.

Checklist:

  • Securely signed commits
  • Component(s) with PHPDoc blocks, only if necessary or adds value (without duplication)
  • Unit testing, with >80% coverage
  • User guide updated
  • Conforms to style guide

- Return default JSON validation errors for JSON bodies or explicit JSON Accept headers
- Stop treating XHR/AJAX requests as JSON automatically
- Document the behavior and update FormRequest tests

Signed-off-by: memleakd <[email protected]>
@github-actions github-actions Bot added the 4.8 PRs that target the `4.8` branch. label May 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

4.8 PRs that target the `4.8` branch.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant