htmx, validate before ajax request
Follow this article to implement htmx validation: https://marcus-obst.de/blog/bootstrap-validation-with-htmx.
The original code is as follows:
// Source: https://gist.github.com/marcus-at-localhost/c9f0a34a2e19d666fd95f61f002ea516
htmx.defineExtension('bs-validation', {
onEvent: function (name, evt, data) {
if (name !== "htmx:afterProcessNode") {
return;
}
console.log('event ' + name);
let form = evt.detail.elt;
// Check if the trigger attribute and submit event exist for the form
if (!form.hasAttribute('hx-trigger')) {
// Set the trigger for the custom event bs-send
form.setAttribute('hx-trigger', 'bs-send');
// Attach the event only once
form.addEventListener('submit', function (event) {
if (form.checkValidity()) {
// Trigger the custom event hx-trigger="bs-send"
htmx.trigger(form, "bsSend");
console.log('bsSend');
}
console.log('prevent');
event.preventDefault();
event.stopPropagation();
form.classList.add('was-validated');
}, false);
}
}
});
However, it didn't work as expected. To make it work, change the first parameter of form.addEventListener from "submit" to "htmx:configRequest," and then it worked.