Creating an HTMX button to save data from a form that has different actions based on the response
17:08 23 Dec 2025

Let's say that I have the following HTML form as a modal pop-up, taking a name and an age, and then a "save" button:

Name:

Age:

If, instead, I wanted to do this with HTMX, I might do it like this:

Name:

Age:

The issue that I have with the HTMX is that when the "/formcheck" endpoint is called, it will either return with a 200 (because the data validation and saving was successful) or a 400 (because data validation failed, and the field(s) with errors will be listed in the response).

If I use an hx-target in the button, then it will replace whatever I put, no matter if the data saved correctly or if there was an error. My knowledge of HTMX is rudimentary, and I've been able to build pages that swap out specific tags with the proper IDs and classes, but I don't know how to implement this when there are divergent paths: either stating that the data saved properly and closing the modal OR leaving the modal open to highlight the data fields with invalid data.

What is the proper way to handle data validation in HTMX with a save button when I don't know if everything will pass validation on the back-end or return an error?

I am fully aware that I may be missing a specific design pattern or function of HTMX, and I will be grateful for any light that you can shed on this issue, especially with links to documentation or tutorials that explain simply and clearly how to approach this.

htmx