Day's Night
Day's Night

Reputation: 653

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.

Upvotes: 47

Views: 43246

Answers (5)

Louay Al-osh
Louay Al-osh

Reputation: 3405

You can use async/await with yup custom validator

let field = yup.string().test(
'test-id',
'error message in case of fail',
 async function validateValue(value){
  try{
    
     // validation logic
     return false; // or true as you see fit

  } catch(error){

  }
});

return true for the values you accept

return false for the values you reject

Make sure you always return a boolean, or add a finally block if you don't have that guarantees yourself.

Upvotes: 9

H S W
H S W

Reputation: 7119

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

Upvotes: 5

Rahul Gupta
Rahul Gupta

Reputation: 10141

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

Upvotes: 0

Tomas Dohnal
Tomas Dohnal

Reputation: 2025

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

Upvotes: 14

이석규
이석규

Reputation: 459

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.

Upvotes: 45

Related Questions