25
votes

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

4

4 Answers

25
votes
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.

3
votes

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
        }),
    ),
})
1
votes

Here is how to async validate with API call:

const validationSchema = Yup.object().shape({
  username: Yup.string().test('checkDuplUsername', 'same name exists', function (value) {
    if (!value) {
      const isDuplicateExists = await checkDuplicate(value);
      console.log("isDuplicateExists = ", isDuplicateExists);
      return !isDuplicateExists;
    }
    // WHEN THE VALUE IS EMPTY RETURN `true` by default
    return true;
  }),
});

function checkDuplicate(valueToCheck) {
  return new Promise(async (resolve, reject) => {
    let isDuplicateExists;

    // EXECUTE THE API CALL TO CHECK FOR DUPLICATE VALUE
    api.post('url', valueToCheck)
    .then((valueFromAPIResponse) => {
      isDuplicateExists = valueFromAPIResponse; // boolean: true or false
      resolve(isDuplicateExists);
    })
    .catch(() => {
      isDuplicateExists = false;
      resolve(isDuplicateExists);
    })
  });
}
0
votes

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);
    });
  }
 ),
});