Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useAsyncValidator): new options #1695

Merged
merged 1 commit into from Jun 17, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 15 additions & 5 deletions packages/integrations/useAsyncValidator/index.ts
@@ -1,41 +1,51 @@
import type { MaybeRef } from '@vueuse/shared'
import { until } from '@vueuse/shared'
import Schema from 'async-validator'
import type { Rules, ValidateError } from 'async-validator'
import type { Rules, ValidateError, ValidateOption } from 'async-validator'
import type { Ref } from 'vue-demi'
import { computed, ref, unref, watchEffect } from 'vue-demi'

type AsyncValidatorError = Error & {
export type AsyncValidatorError = Error & {
errors: ValidateError[]
fields: Record<string, ValidateError[]>
}

interface UseAsyncValidatorReturn {
export interface UseAsyncValidatorReturn {
pass: Ref<boolean>
errorInfo: Ref<AsyncValidatorError | null>
isFinished: Ref<boolean>
errors: Ref<AsyncValidatorError['errors'] | undefined>
errorFields: Ref<AsyncValidatorError['fields'] | undefined>
}

export interface UseAsyncValidatorOptions {
/**
* @see https://github.com/yiminghe/async-validator#options
*/
validateOption?: ValidateOption
}

/**
* Wrapper for async-validator.
*
* @see https://vueuse.org/useAsyncValidator
* @see https://github.com/yiminghe/async-validator
*/
export function useAsyncValidator(value: MaybeRef<Record<string, any>>, rules: MaybeRef<Rules>): UseAsyncValidatorReturn & PromiseLike<UseAsyncValidatorReturn> {
export function useAsyncValidator(value: MaybeRef<Record<string, any>>, rules: MaybeRef<Rules>, options: UseAsyncValidatorOptions = {}): UseAsyncValidatorReturn & PromiseLike<UseAsyncValidatorReturn> {
const errorInfo = ref<AsyncValidatorError | null>()
const isFinished = ref(false)
const pass = ref(false)
const errors = computed(() => errorInfo.value?.errors || [])
const errorFields = computed(() => errorInfo.value?.fields || {})

const { validateOption = {} } = options

watchEffect(async () => {
isFinished.value = false
pass.value = false
const validator = new Schema(unref(rules))
try {
await validator.validate(unref(value))
await validator.validate(unref(value), validateOption)
pass.value = true
errorInfo.value = null
}
Expand Down