5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-23 01:26:22 +00:00
panel/app/javascript/controllers/form_validation_controller.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-06-19 16:12:54 +00:00
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["invalid", "submitting"];
// @todo Stimulus >1
get submittingIdValue() {
return this.element.dataset?.formValidationSubmittingIdValue;
}
// @todo Stimulus >1
get invalidIdValue() {
return this.element.dataset?.formValidationInvalidIdValue;
}
2024-06-19 16:12:54 +00:00
connect() {
this.element.setAttribute("novalidate", true);
for (const input of this.element.elements) {
if (input.type === "button" || input.type === "submit") continue;
if (input.dataset.action) {
input.dataset.action = `${input.dataset.action} htmx:validation:validate->form-validation#submit`;
} else {
input.dataset.action = "htmx:validation:validate->form-validation#submit";
}
}
}
submit(event = undefined) {
if (this.submitting) return;
this.submitting = true;
2024-06-19 16:12:54 +00:00
event?.preventDefault();
if (this.element.reportValidity()) {
this.element.classList.remove("was-validated");
if (!this.element.getAttributeNames().some(x => x.startsWith("hx-"))) this.element.submit();
window.dispatchEvent(new CustomEvent("notification:show", { detail: { value: this.submittingIdValue } }));
} else {
event?.stopPropagation();
this.element.classList.add("was-validated");
window.dispatchEvent(new CustomEvent("notification:show", { detail: { value: this.invalidIdValue } }));
2024-06-19 16:12:54 +00:00
}
this.submitting = false;
2024-06-19 16:12:54 +00:00
}
}