首页 > 解决方案 > 使用 yup 模式的 Formik 异步字段验证

问题描述

就我而言,我有一个是的模式表单验证。例如:

const form = yup.object().shape({
firstName: yup.string().nullable().required(),
lastName: yup.string().nullable().required(),
country: yup.string().nullable().required()
    .test('validator', 'country is incorrect', value => {
        return new Promise((resolve, reject) => {
            api.post('url', value)
            .then(() => 
                  resolve(false))
            .catch(() => 
                  resolve(true)
        })
    }
});

另外,我想异步验证国家字段。


流程应该如下:

我遇到的问题:

我尝试使用 .test() 从是的,但验证器的顺序是错误的。

例如,在这种情况下,我想执行所需的验证器,并且只有当它成功通过且没有错误时才运行 .test() (异步验证)。

如何使用 Formik 和 Yup 实现这种行为?

标签: javascriptreactjsformikyup

解决方案


这是如何实现的:

const form = yup.object().shape({
  firstName: yup.string().nullable().required(),
  lastName: yup.string().nullable().required(),
  country: yup.string().nullable().required()
    .test('validator', 'country is incorrect', value => {
      if (!_.isEmpty(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);
    })
  });
}

推荐阅读