Skip to content

Instantly share code, notes, and snippets.

@marcus-at-localhost
Last active October 30, 2023 14:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save marcus-at-localhost/c9f0a34a2e19d666fd95f61f002ea516 to your computer and use it in GitHub Desktop.
Save marcus-at-localhost/c9f0a34a2e19d666fd95f61f002ea516 to your computer and use it in GitHub Desktop.
[Bootstrap Form Validation HTMX Extension] See example: https://jsfiddle.net/hxjvw62L/ #htmx #bootstrap
htmx.defineExtension('bs-validation', {
onEvent: function (name, evt, data) {
let form = evt.detail.elt;
// check if trigger attribute and submit event exists
// for the form
if(!form.hasAttribute('hx-trigger')){
// set trigger for custom event bs-send
form.setAttribute('hx-trigger','bs-send');
// and attach the event only once
form.addEventListener('submit', function (event) {
if (form.checkValidity()) {
// trigger custom event hx-trigger="bs-send"
htmx.trigger(form, "bsSend");
console.log('bsSend')
}
// focus the first :invalid field
let invalidField = form.querySelector(':invalid');
if(invalidField) {
invalidField.focus();
}
console.log('prevent')
event.preventDefault()
event.stopPropagation()
form.classList.add('was-validated')
}, false)
}
}
});
  1. Add HTMX attributes to the form.
<form 

  hx-post="/foo"
  hx-ext="bs-validation"

  class="row g-3 needs-validation" 
  novalidate
>
  
</form>

See example: https://getbootstrap.com/docs/5.1/forms/validation/#custom-styles

  1. on first load the extension adds hx-trigger="bs-validation" to the form and a submit event listener to deal with the custom styles (in order for bootstrap custom styles appear, novalidate bypasses browsers native form validation)
@vu3jej
Copy link

vu3jej commented Apr 18, 2023

Some Alpine.js magic if that is an option.

<form id="import-form"
      class="needs-validation"
      novalidate
      hx-post="/test"
      hx-trigger="post-form"
      @submit.prevent="if (!$el.checkValidity()) { event.stopPropagation() } else { $dispatch('post-form') } $el.classList.add('was-validated')">

@marcus-at-localhost
Copy link
Author

marcus-at-localhost commented Apr 18, 2023

Some Alpine.js magic if that is an option.

much appreciated! Thank you @vu3jej !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment