Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 28 ยท HTMX Basics

Forms, Validation and Submissions

Submit forms with hx-post, return validation errors as HTML, validate fields on blur, disable buttons with hx-disabled-elt and confirm risky actions.

Forms are where HTMX shines. A classic form submission reloads the whole page, even when the server only wants to say "that email is already taken". With HTMX the form stays on screen, the request goes out in the background, and the server answers with a piece of HTML: the same form with error messages, or a success note.

This lesson covers the whole loop: sending a form, showing validation errors, checking a single field when the user leaves it, preventing double submits, and asking for confirmation. Everything uses the ideas from Targets and Swap Strategies.

Our examples never post to a real server. The in-page mock server (see Setting Up) answers every request, and the sandbox forbids real submissions anyway.

hx-post on a form

Put hx-post on the <form> element and HTMX does three things for you: it listens for the submit event (and cancels the browser's own submission), it collects every named field into the request body, and it swaps the response into the target.

HTML
<form hx-post="/signup" hx-target="this" hx-swap="outerHTML">
  <input name="email" type="email" required>
  <button>Sign up</button>
</form>

Details worth knowing:

  • Encoding. The body is sent as application/x-www-form-urlencoded, exactly like a normal form. Add hx-encoding="multipart/form-data" when the form has a file input.
  • Which values are sent. For GET requests, the values go into the query string. For POST, PUT, PATCH and DELETE, an element inside a form also sends the enclosing form's values, so a "Save" button with its own hx-post still submits the whole form.
  • Browser validation still works. Attributes such as required and type="email" block the request until the fields are valid, because HTMX validates the form before sending.
  • Unchecked checkboxes and disabled inputs are not sent, just like in HTML.

Returning validation errors as HTML

Where do error messages come from? From the server. It validates the data, and if something is wrong it returns the form again with messages and the values the user typed. With hx-target="this" and hx-swap="outerHTML", that response replaces the form in place.

Server-side validation

Submit the empty form to see three errors, then fill it in step by step. Notice three design choices:

  1. The server escapes the echoed values (esc). Never put user input into HTML without escaping it, or you create a cross-site scripting hole.
  2. Every input has an id. When a swap replaces the form, HTMX restores focus to the element with the same id, so the user can keep typing.
  3. The error response is a normal 200 page fragment. HTMX does not swap 4xx and 5xx responses by default. Many teams prefer to return 422 Unprocessable Content for failed validation; you can allow that with one event handler, shown in Events, Headers and JavaScript Integration.
flowchart LR
    A["User submits form"] --> B["Server validates"]
    B -->|"errors"| C["Return form with messages"]
    B -->|"valid"| D["Return success HTML"]
    C --> E["HTMX swaps form in place"]
    D --> E

The server decides what the user sees next; HTMX only swaps the answer in.

Validating one field when it loses focus

Waiting until the end of a long form is unfriendly. You can check a single field as soon as the user leaves it. The trick is that an input is allowed to carry hx-post itself. Its default trigger is change; here we use blur and the changed modifier so a request goes out only when the value is different from the last time.

Inline validation on blur

Type ada, click outside the input, and the message appears under it. Type the same value again and leave: no request is sent, because of changed. The server route only looks at one field and returns a few words of HTML. You can build the final submit endpoint on top of the same validation function, so the rules live in one place.

Validate on the server even if you validate in the browser too. The server is the only place you can trust, and with HTMX it costs you almost nothing extra: the same checks produce the inline messages and the final answer.

Preventing double submits with hx-disabled-elt

A slow request invites a second click. hx-disabled-elt takes a selector (it understands this, closest, find, next and previous too) and sets the disabled attribute on the matching elements for the duration of the request. Put it on the form and point it at the button:

HTML
<form hx-post="/save" hx-disabled-elt="find button">

When the request finishes, HTMX removes disabled again.

Asking for confirmation

hx-confirm="Delete this account?" makes HTMX show the browser's confirm() dialog before sending. If the user cancels, nothing is sent. Browsers block confirm() in our sandboxed preview, so the example below replaces the dialog with its own panel. HTMX fires an htmx:confirm event before every request; if you call preventDefault() you can ask in any way you like and later call issueRequest(true) to continue.

Disabled button and custom confirm

Press Save, confirm, and watch the button stay disabled for the 1.5 seconds the mock server takes. Then try "Cancel": no request leaves. In your own site you would normally just write hx-confirm and accept the native dialog.

A note on hx-boost

hx-boost="true" on a container (often <body>) turns every link and form inside it into an AJAX request that swaps the <body> and updates the address bar. If JavaScript is missing, links and forms still work normally, which makes boost a very cheap way to speed up a classic server-rendered site. Boost depends on browser history, which the preview sandbox does not allow, so it is only described here and covered in full in URLs, History and Navigation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A form has hx-post="/signup". What does HTMX do with the browser's normal submission?

    HTMX listens for submit, prevents the default navigation and issues an AJAX request with the form's named fields.
  2. 2. The server returns a 422 status with an HTML error fragment. What happens by default in HTMX?

    By default only successful responses are swapped. Either return 200 with the error HTML or configure the swap in htmx:beforeSwap.
  3. 3. What does hx-disabled-elt="find button" on a form do?

    The matching element receives the disabled attribute during the request, which stops double submits.
  4. 4. Why should the server escape the values it echoes back into a returned form?

    Unescaped input in HTML lets an attacker inject scripts. Always escape user data when you build HTML on the server.
  5. 5. Which trigger value validates an input only when the user leaves it and the value actually changed?

    blur fires when the field loses focus, and changed skips the request when the value is the same as last time.

Summary

  • hx-post on a form sends its named fields (urlencoded by default, multipart with hx-encoding) and swaps the response where hx-target says.
  • Validation lives on the server: return the form again with errors and echoed (escaped) values, or return a success fragment.
  • Give inputs an id so focus survives a swap.
  • An input can carry its own hx-post with hx-trigger="blur changed" for inline checks.
  • hx-disabled-elt blocks double submits; hx-confirm and the htmx:confirm event ask before sending.
  • hx-boost upgrades links and forms progressively; it is covered with history in a later lesson.

Continue with Loading States, Indicators and Feedback.