(
value: MaybeRefOrGetter<Record<string, any>>,
rules: MaybeRefOrGetter<Rules>,
options: UseAsyncValidatorOptions = {},
)
| 53 | * @see https://github.com/yiminghe/async-validator |
| 54 | */ |
| 55 | export function useAsyncValidator( |
| 56 | value: MaybeRefOrGetter<Record<string, any>>, |
| 57 | rules: MaybeRefOrGetter<Rules>, |
| 58 | options: UseAsyncValidatorOptions = {}, |
| 59 | ): UseAsyncValidatorReturn & PromiseLike<UseAsyncValidatorReturn> { |
| 60 | const { |
| 61 | validateOption = {}, |
| 62 | immediate = true, |
| 63 | manual = false, |
| 64 | } = options |
| 65 | |
| 66 | const valueRef = toRef(value) |
| 67 | |
| 68 | const errorInfo = shallowRef<AsyncValidatorError | null>(null) |
| 69 | const isFinished = shallowRef(true) |
| 70 | const pass = shallowRef(!immediate || manual) |
| 71 | const errors = computed(() => errorInfo.value?.errors || []) |
| 72 | const errorFields = computed(() => errorInfo.value?.fields || {}) |
| 73 | |
| 74 | const validator = computed(() => new AsyncValidatorSchema(toValue(rules))) |
| 75 | |
| 76 | const execute = async (): Promise<UseAsyncValidatorExecuteReturn> => { |
| 77 | isFinished.value = false |
| 78 | pass.value = false |
| 79 | |
| 80 | try { |
| 81 | await validator.value.validate(valueRef.value, validateOption) |
| 82 | pass.value = true |
| 83 | errorInfo.value = null |
| 84 | } |
| 85 | catch (err) { |
| 86 | errorInfo.value = err as AsyncValidatorError |
| 87 | } |
| 88 | finally { |
| 89 | isFinished.value = true |
| 90 | } |
| 91 | |
| 92 | return { |
| 93 | pass: pass.value, |
| 94 | errorInfo: errorInfo.value, |
| 95 | errors: errors.value, |
| 96 | errorFields: errorFields.value, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | if (!manual) { |
| 101 | watch( |
| 102 | [valueRef, validator], |
| 103 | () => execute(), |
| 104 | { immediate, deep: true }, |
| 105 | ) |
| 106 | } |
| 107 | |
| 108 | const shell = { |
| 109 | isFinished, |
| 110 | pass, |
| 111 | errors, |
| 112 | errorInfo, |
no test coverage detected