function checkInputValidation(a: Event, callout: (errors: string[], valid: boolean) => void) { if ((a.target as HTMLInputElement).validity) { let el = (a.target as HTMLInputElement); if (el.validity) { let errors = [ el.validity.badInput ? "bad input" : null, el.validity.customError ? "custom error" : null, el.validity.patternMismatch ? "pattern mismatch" : null, el.validity.rangeOverflow ? "range overflow" : null, el.validity.rangeUnderflow ? "range underflow" : null, el.validity.stepMismatch ? "step mismatch" : null, el.validity.tooLong ? "too long" : null, el.validity.tooShort ? "too short" : null, el.validity.typeMismatch ? "type mismatch" : null, el.validity.valueMissing ? "value missing" : null].filter(i => !!i) callout(errors as string[], el.validity.valid != undefined ? el.validity.valid : true); } } } type ValidatableElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; const invalidListeners = new WeakMap(); export const validate = { mounted: (el: ValidatableElement, bind: { value: (errors: string[], valid: boolean) => void, arg?: string }) => { if (!el || !el.willValidate) return; switch (el.nodeName) { case "INPUT": case "TEXTAREA": el.onblur = (arg) => checkInputValidation(arg, bind.value); break; case "SELECT": el.onchange = (arg) => checkInputValidation(arg, bind.value); break; } el.oninvalid = (arg) => checkInputValidation(arg, bind.value); if (el.form) { const form = el.form; const listener: EventListener = () => checkInputValidation({ target: el } as any, bind.value); invalidListeners.set(el, { form, listener }); form.addEventListener('invalid', listener); } if (bind.arg == "immediate") el.reportValidity(); else checkInputValidation({ target: el } as any, bind.value) }, unmounted: (el: ValidatableElement) => { if (!el) return; const entry = invalidListeners.get(el); if (entry) entry.form.removeEventListener('invalid', entry.listener); invalidListeners.delete(el); el.oninvalid = null; el.onblur = null; el.onchange = null; }, }