rainbox.email/assets/ts/forms.ts

44 lines
1.5 KiB
TypeScript

/*
* For labels to update their state (css selectors based on the value attribute)
*/
import {ValidationError} from "wms-core/db/Validator";
export function updateInputs(): void {
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input, textarea').forEach(el => {
if (!el.dataset.inputSetup) {
el.dataset.inputSetup = 'true';
if (el.type !== 'checkbox') {
el.setAttribute('value', el.value);
el.addEventListener('change', () => {
el.setAttribute('value', el.value);
});
}
}
});
}
document.addEventListener('DOMContentLoaded', () => {
updateInputs();
});
export function applyFormMessages(
formElement: HTMLFormElement,
messages: { [p: string]: ValidationError<unknown> },
): void {
for (const fieldName of Object.keys(messages)) {
const field = formElement.querySelector('#field-' + fieldName);
if (!field) continue;
let parent = field.parentElement;
while (parent && !parent.classList.contains('form-field')) parent = parent.parentElement;
let err = field.querySelector('.error');
if (!err) {
err = document.createElement('div');
err.classList.add('error');
parent?.insertBefore(err, parent.querySelector('.hint') || parent);
}
err.innerHTML = `<i data-feather="x-circle"></i> ${messages[fieldName].message}`;
}
}