Async validation with Formik, Yup and React

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.

Leave a Comment