vue3-validate-directive
Version:
A flexible Vue 3 directive for form validation with support for sync/async functions, RegExp, and string patterns
63 lines (62 loc) • 2.11 kB
JavaScript
import { nextTick as l } from "vue";
const d = (i) => {
const {
defaultMessage: r = "Invalid value"
} = i ?? {}, n = (e, t, o) => {
t.setCustomValidity(e ? "" : o.value.msg || r), t.reportValidity();
}, u = (e, t, o) => {
e.then((a) => {
t.setCustomValidity(a ? "" : o.value.msg || r);
}).catch((a) => {
t.setCustomValidity(a.message);
}).finally(() => {
t.reportValidity();
});
}, c = (e, t) => {
l(
() => {
const o = t.modifiers.checked ? e.checked : e.value, a = t.value.f;
if (typeof a == "string")
n(new RegExp(a).test(o), e, t);
else if (a instanceof RegExp)
n(a.test(o), e, t);
else if (typeof a == "function")
try {
const s = a(o);
typeof s == "boolean" ? n(s, e, t) : s instanceof Promise && u(s, e, t);
} catch (s) {
console.error("error validating", s.message);
}
else
console.warn("validate function invalid. Expected string, RegExp, or function. Got:", a);
}
);
};
return {
beforeMount: (e, t) => {
if (!e.matches("input,textarea,select")) {
console.warn("v-validate is only supported on input, textarea, and select elements", e);
return;
}
e.$inputHandler = () => c(e, t), e.addEventListener("input", e.$inputHandler), e.$origValueAccessor = Object.getOwnPropertyDescriptor(e.__proto__, "value"), Object.defineProperty(e, "value", {
...e.$origValueAccessor,
set: function(o) {
e.$origValueAccessor.set.call(this, o), c(e, t);
}
}), c(e, t);
},
beforeUnmount: (e, t) => {
e.matches("input,textarea,select") && (e.$origValueAccessor && (Object.defineProperty(e, "value", e.$origValueAccessor), delete e.$origValueAccessor), e.$inputHandler && (e.removeEventListener("input", e.$inputHandler), delete e.$inputHandler));
}
};
}, f = (i, r) => {
i.directive("validate", d(r));
}, v = () => {
}, V = {
install: f,
uninstall: v
};
export {
V as VueValidateDirective,
V as default
};