Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
Day's Night Avatar asked Apr 23 '19 12:04

Day's Night


3 Answers

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.

like image 195
이석규 Avatar answered Sep 25 '22 02:09

이석규


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         }),     ), }) 
like image 28
Tomas Dohnal Avatar answered Sep 23 '22 02:09

Tomas Dohnal


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);
    });
  }
 ),
});
    
like image 29
H S Progr Avatar answered Sep 27 '22 02:09

H S Progr