mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-25 15:15:23 +03:00
39 lines
784 B
TypeScript
39 lines
784 B
TypeScript
import { reactive, watch, type Ref } from 'vue';
|
|
|
|
type UseValidationRule<T> = {
|
|
validator: (value: T) => boolean;
|
|
message: string;
|
|
};
|
|
|
|
function isFalsyOrHasThrown(cb: () => boolean) {
|
|
try {
|
|
return !cb();
|
|
} catch (_) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
export function useValidation<T>({ source, rules }: { source: Ref<T>; rules: UseValidationRule<T>[] }) {
|
|
const state = reactive<{
|
|
message: string;
|
|
status: undefined | 'error';
|
|
}>({
|
|
message: '',
|
|
status: undefined,
|
|
});
|
|
|
|
watch([source], () => {
|
|
state.message = '';
|
|
state.status = undefined;
|
|
|
|
for (const rule of rules) {
|
|
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
|
|
state.message = rule.message;
|
|
state.status = 'error';
|
|
}
|
|
}
|
|
});
|
|
|
|
return state;
|
|
}
|