HTMX - Validation



HTMX validation works with HTML5 Validation API as it will not trigger any request for a form if the validatable input field is invalid. This works the same on Ajax requests as well as WebSockets sends both. It will fire events around validation that can be used to hook in custom validation and error handling.

  • htmx:validation:validate: Used to add custom validation logics.
  • htmx:validation:failed: Used to indicate an invalid input.
  • htmx:validation:halted: Used to show validation errors.

Example of HTMX Validation

Here in this following example hx-on attribute catch the htmx:validation:validate event and require the inout value 'tutorialspoint'. Remember all the client-side validations should be re-done on the server side because this can be always bypassed.

<form id="example-form" hx-post="/test">
   <input
      name="example"
      // Reset the validation on keyup
      onkeyup="this.setCustomValidity('')"
      hx-on:htmx:validation:validate="if(this.value != 'tutorialspoint') {
      // Set the validation error
      this.setCustomValidity('Please enter the value tutorialspoint')
      // Report the issue
      htmx.find('#example-form').reportValidity() 
      }"
      />
</form>

How to Validate Non-form Elements?

You can set a true value on hx-validate attribute to validate a non-form element before they make any request. Form elements validate before they make any request by default.

Example of Non-form Element Validating

In this following example a non-form element is validating before making a request.

  • The input field has the required attribute, making it mandatory.
  • The div element uses hx-get to send a GET request to /validate-username when clicked.
  • The hx-validate="true" attribute ensures that the input field is validated before the request is made.
  • The response from the server will be displayed in the div with the ID result.
<input type="text" id="username" required placeholder="Enter your username" />
<div
   hx-get="/validate-username"
   hx-validate="true"
   hx-trigger="click"
   hx-target="#result"
   >
   Validate Username
</div>
<div id="result"></div>
Advertisements