Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lysender/a36143c002a84ed2c166bf7567b1a913 to your computer and use it in GitHub Desktop.
Save lysender/a36143c002a84ed2c166bf7567b1a913 to your computer and use it in GitHub Desktop.
HTMX - Allow HTTP error 400 and 422 swap content to enable showing validation errors

Still a newbie to HTMX.

I was writing some form submit interaction and realized that HTMX won't swap/render if the HTTP status code is not 2xx.

For 404, 500 or 503 errors, I think it's fair enough.

For my use case, I'm returning error 400 or 422 for validation errors. I'm returning the form back with some error decorations for example.

According to the docs, I can change that behavior.

So I did.

document.body.addEventListener('htmx:beforeSwap', function(evt) {
  // Allow 422 and 400 responses to swap
  // We treat these as form validation errors
  if (evt.detail.xhr.status === 422 || evt.detail.xhr.status === 400) {
    evt.detail.shouldSwap = true;
    evt.detail.isError = false;
  }
});
@fujohnwang
Copy link

you can use htmx.on to write less code ;)

https://wfq.gumroad.com/l/htmx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment