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
Question
I want to make async validation with formik and validationschema with yup but i can't find the example or demo.
Solution
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.
Solution
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
}),
),
})