htmx interview question · Most asked
How do you handle form validation errors with htmx?
Summary
Keep browser validation (required, type=email) for instant feedback, and always validate on the server. On errors, return the form with the user's values and messages, ideally with status 422. htmx 2 doesn't swap 4xx responses by default, so add a responseHandling rule that swaps 422, or use the response-targets extension (hx-target-422).
Longer Answer
A common shortcut is returning errors with 200 so htmx swaps them, but then monitoring and tests can't tell success from failure. Accessible error markup links the message with aria-describedby and marks the field aria-invalid. In htmx 4, 4xx/5xx responses are swapped by default, and hx-status gives per-code control.
Code Example
<meta name="htmx-config" content='{"responseHandling": [{"code": "204", "swap": false},
{"code": "422", "swap": true}, {"code": "[23]..", "swap": true}, {"code": "[45]..", "swap": false, "error": true}]}'>
Key Points
- Browser validation plus server validation.
- Return the form with values and messages.
- 422 + responseHandling rule in htmx 2.
- Accessible error markup.
Deep dive: htmx: Build Interactive Web Apps with HTML: Forms the htmx Way
Explanation
What interviewers look for
Knowing that htmx 2 skips 4xx swaps and a clean fix, plus server-side validation.
More most-asked htmx questions
- What security risks are specific to htmx, and how do you mitigate them?
- How does htmx compare with React or Vue?
- What is htmx?
- What do hx-get, hx-post, hx-put, hx-patch and hx-delete do, and how are values sent?
- What is hx-target, and what relative selectors does it support?
- What swap styles does hx-swap support?
- How does hx-trigger work? Give examples of modifiers and special triggers.
- Explain the htmx request lifecycle.