I want to make async validation with formik and validationschema with yup but i can't find the example or demo.
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.
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 }), ), })
For example I am using fake promise, It can be done as follow:
const Schema = yup.object().shape({
password: yup
.string()
.test("validPassword","Password requires one special character",
function (value) {
return new Promise((resolve) => {
setTimeout(() => {
if (
/^[0-9A-Za-z]*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?][0-9a-zA-Z]*$/.test(
value
)
) {
resolve(true);
} else {
resolve(false);
}
}, 100);
});
}
),
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With