2022-07-29 10:56:04 +02:00
|
|
|
import _ from 'lodash';
|
2022-04-11 22:47:05 +02:00
|
|
|
import { reactive, watch, type Ref } from 'vue';
|
|
|
|
|
2022-07-29 10:56:04 +02:00
|
|
|
type ValidatorReturnType = unknown;
|
|
|
|
|
|
|
|
interface UseValidationRule<T> {
|
|
|
|
validator: (value: T) => ValidatorReturnType;
|
2022-04-11 23:08:50 +02:00
|
|
|
message: string;
|
2022-07-29 10:56:04 +02:00
|
|
|
}
|
2022-04-11 22:47:05 +02:00
|
|
|
|
2022-07-29 10:56:04 +02:00
|
|
|
export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
|
2022-05-09 17:40:29 +02:00
|
|
|
try {
|
2022-07-29 10:56:04 +02:00
|
|
|
const returnValue = cb();
|
|
|
|
|
|
|
|
if (_.isNil(returnValue)) return true;
|
|
|
|
|
|
|
|
return returnValue === false;
|
2022-05-09 17:40:29 +02:00
|
|
|
} catch (_) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-11 22:47:05 +02:00
|
|
|
export function useValidation<T>({ source, rules }: { source: Ref<T>; rules: UseValidationRule<T>[] }) {
|
|
|
|
const state = reactive<{
|
2022-04-11 23:08:50 +02:00
|
|
|
message: string;
|
|
|
|
status: undefined | 'error';
|
2022-07-29 10:56:04 +02:00
|
|
|
isValid: boolean;
|
2022-04-11 22:47:05 +02:00
|
|
|
}>({
|
|
|
|
message: '',
|
2022-04-11 23:08:50 +02:00
|
|
|
status: undefined,
|
2022-07-29 10:56:04 +02:00
|
|
|
isValid: false,
|
2022-04-11 23:08:50 +02:00
|
|
|
});
|
2022-04-11 22:47:05 +02:00
|
|
|
|
2022-07-29 10:56:04 +02:00
|
|
|
watch(
|
|
|
|
[source],
|
|
|
|
() => {
|
|
|
|
state.message = '';
|
|
|
|
state.status = undefined;
|
2022-04-11 23:08:50 +02:00
|
|
|
|
2022-07-29 10:56:04 +02:00
|
|
|
for (const rule of rules) {
|
|
|
|
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
|
|
|
|
state.message = rule.message;
|
|
|
|
state.status = 'error';
|
|
|
|
}
|
2022-04-11 22:47:05 +02:00
|
|
|
}
|
2022-07-29 10:56:04 +02:00
|
|
|
|
|
|
|
state.isValid = state.status !== 'error';
|
|
|
|
},
|
|
|
|
{ immediate: true },
|
|
|
|
);
|
2022-04-11 22:47:05 +02:00
|
|
|
|
|
|
|
return state;
|
|
|
|
}
|