Handling form errors in htmx

21 points by yawaramin


adriano

I think this is a pretty neat generalized solution for anyone comfortable using the browser’s validation UI.

With that said, it’s not a very “htmx way”, as it uses JSON response payloads. To do validation a more “htmx way”, I recommend using the response targets extension instead, and using appropriate HTTP status codes to indicate different classes of errors.

You can use either HTML5 validation or client-side javascript validation where it makes sense. But any form fields requiring a server round trip (e.g. username availability) can simply use a debounced data-hx-trigger (e.g. data-hx-trigger="keyup changed delay:300ms" coupled with data-hx-target-[4,5]*="#username_errors" targeting the HTML element where errors for that field should be rendered.

This feels like a more natural htmx solution to me.