Question

Async validation with Formik, Yup and React

I want to make async validation with formik and validationschema with yup but i can't find the example or demo.

 46  41031  46
1 Jan 1970

Solution

 45
const validationSchema = Yup.object().shape({
    username:
        Yup.string()
            .test('checkDuplUsername', 'same name exists', function (value) {
                return new Promise((resolve, reject) => {
                    kn.http({
                        url: `/v1/users/${value}`,
                        method: 'head',
                    }).then(() => {
                        // exists
                        resolve(false)
                    }).catch(() => {
                        // note exists
                        resolve(true)
                    })
                })
            })
})

Yup provides asynchronous processing through the test method.
(kn is my ajax promise function)
have a nice day.

2019-09-11

Solution

 13

Actually, it can be simplified a bit


const validationSchema = Yup.object().shape({
    username: Yup.string().test('checkEmailUnique', 'This email is already registered.', value =>
        fetch(`is-email-unique/${email}`).then(async res => {
            const { isEmailUnique } = await res.json()

            return isEmailUnique
        }),
    ),
})
2020-11-23