Skip to content

useAsyncValidator

Category
Export Size
719 B
Package
@reause/integrations
Last Changed
5 days ago

Wrapper for async-validator.

Demo

Install

bash
npm i async-validator@^4

Usage

tsx
import type { 
Rules
} from 'async-validator'
import {
useAsyncValidator
} from '@reause/integrations'
import {
useState
} from 'react'
const
rules
:
Rules
= {
name
: {
type
: 'string',
min
: 5,
max
: 20,
required
: true },
age
: {
type
: 'number',
required
: true },
email
: [{
type
: 'email',
required
: true }],
} function
Demo
() {
const [
form
,
setForm
] =
useState
({
name
: '',
age
: '',
email
: '' })
// pass a STABLE object (state/ref/memo) — see the note below const {
pass
,
isFinished
,
errorFields
} =
useAsyncValidator
(
form
,
rules
)
return ( <
form
>
<
input
value={
form
.name} onChange={
e
=>
setForm
({ ...
form
,
name
:
e
.target.value })} />
{errorFields.name?.length ? <
div
>{
errorFields
.name[0].message}</div> : null}
<
button
disabled={!pass}>Submit</button>
{isFinished ? null : <
span
>validating…</span>}
</form> ) }

Type Declarations

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

export interface UseAsyncValidatorExecuteReturn {
    pass: boolean;
    errors: ValidateError[];
    errorInfo: AsyncValidatorError | null;
    errorFields: Record<string, ValidateError[]>;
}

export interface UseAsyncValidatorReturn {
    pass: boolean;
    isFinished: boolean;
    errors: ValidateError[];
    errorInfo: AsyncValidatorError | null;
    errorFields: Record<string, ValidateError[]>;
    execute: () => Promise<UseAsyncValidatorExecuteReturn>;
}

export interface UseAsyncValidatorOptions {
    validateOption?: ValidateOption;
    immediate?: boolean;
    manual?: boolean;
}

export function useAsyncValidator(value: Record<string, any>, rules: Rules, options?: UseAsyncValidatorOptions): UseAsyncValidatorReturn & PromiseLike<UseAsyncValidatorReturn>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
6ea56 - fix(integrations): resolve useAsyncValidator audit findings (#795)
d736e - feat(integrations): add useAsyncValidator (#79)

Released under the MIT License. v0.1.8