useAsyncValidation
useAsyncValidation(validator: Function)
provides the async validation logic to any Field.
const [asyncStatus, validationAsyncAttr] = useAsyncValidation(fn);
Arguments
validator
: function
- A function which receives the value of the field and returns a promise.
Returns
(validationAsyncProps
): array
An array that holds:
-
asyncStatus
: object-
A plain object that holds a prop named
status
and a prop namedvalue
. -
status
might be one of the following:- "undefined" : async validation did not start yet
- "asyncStart" : async validation has started
- "asyncSuccess" : the promise has been resolved with success
- "asyncError" : the promise has been rejected
-
value
is the value returned by the promise
-
-
validationAsyncAttr
: object- A plain object which contains all the props that must be spreaded to the Field.
Basic usage
import { Form, Input, useAsyncValidation } from 'usetheform'
Preview
Live Editor
function FormAsyncValidation() { const asyncTest = value => new Promise((resolve, reject) => { setTimeout(() => { if (value.length <= 3) { reject("Error"); } else resolve("Success"); }, 1500); }); const [asyncStatus, validationProps] = useAsyncValidation(asyncTest) return ( <Form> <Input type="text" name="name" touched placeholder="Name" {...validationProps} /> {asyncStatus.status === undefined && <label className="vl">Async Check Not Started Yet</label>} {asyncStatus.status === "asyncStart" && <label className="vl">Checking...</label>} {asyncStatus.status === "asyncError" && <label className="vl">{asyncStatus.value}</label>} {asyncStatus.status === "asyncSuccess" && <label className="vl">{asyncStatus.value}</label>} </Form> ) }