mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-04-22 15:56:15 -04:00
feat: catch throw on validation
This commit is contained in:
parent
b89db3c8d0
commit
a60f64f744
1 changed files with 9 additions and 1 deletions
|
@ -5,6 +5,14 @@ type UseValidationRule<T> = {
|
|||
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;
|
||||
|
@ -19,7 +27,7 @@ export function useValidation<T>({ source, rules }: { source: Ref<T>; rules: Use
|
|||
state.status = undefined;
|
||||
|
||||
for (const rule of rules) {
|
||||
if (!rule.validator(source.value)) {
|
||||
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
|
||||
state.message = rule.message;
|
||||
state.status = 'error';
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue