fix(validation): proper rules

This commit is contained in:
Corentin Thomasset 2022-04-11 23:08:50 +02:00
parent b44539c182
commit 11d8110226
No known key found for this signature in database
GPG key ID: DBD997E935996158
2 changed files with 16 additions and 13 deletions

View file

@ -1,27 +1,30 @@
import { reactive, watch, type Ref } from 'vue'; import { reactive, watch, type Ref } from 'vue';
type UseValidationRule<T> = { type UseValidationRule<T> = {
validator: (value: T) => boolean validator: (value: T) => boolean;
message: string message: string;
} };
export function useValidation<T>({ source, rules }: { source: Ref<T>; rules: UseValidationRule<T>[] }) { export function useValidation<T>({ source, rules }: { source: Ref<T>; rules: UseValidationRule<T>[] }) {
const state = reactive<{ const state = reactive<{
message: string, message: string;
status: undefined | 'error' status: undefined | 'error';
}>({ }>({
message: '', message: '',
status: undefined status: undefined,
}) });
watch([source], () => { watch([source], () => {
state.message = '';
state.status = undefined;
for (const rule of rules) { for (const rule of rules) {
if (!rule.validator(source.value)) { if (!rule.validator(source.value)) {
state.message = rule.message state.message = rule.message;
state.status = 'error' state.status = 'error';
} }
} }
}) });
return state; return state;
} }

View file

@ -110,7 +110,7 @@ const entropyValidation = useValidation({
message: 'Entropy length should be >= 16, <= 32 and be a multiple of 4' message: 'Entropy length should be >= 16, <= 32 and be a multiple of 4'
}, },
{ {
validator: (value) => /^[a-fA-f0-9]?$/.test(value), validator: (value) => /^[a-fA-F0-9]*$/.test(value),
message: 'Entropy should an hexadecimal number' message: 'Entropy should an hexadecimal number'
} }
] ]