javascript - 使用 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)
})
}
});
另外,我想异步验证国家字段。
流程应该如下:
- 应该运行同步验证
- 如果没有同步验证错误
- 然后运行异步验证
- 如果没有 ASYNCHRONOUS 验证表格应该是有效的
我遇到的问题:
我尝试使用 .test() 从是的,但验证器的顺序是错误的。
例如,在这种情况下,我想执行所需的验证器,并且只有当它成功通过且没有错误时才运行 .test() (异步验证)。
如何使用 Formik 和 Yup 实现这种行为?
解决方案
这是如何实现的:
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);
})
});
}
推荐阅读
- jquery - 为什么我不能正确地遍历车把元素?
- python - 单个 DataFrame 中多行的交集
- php - 错误文档 404“消息”指令在 .htaccess 中不起作用
- python - 如何让pygame只加载屏幕上显示的图形
- java - 如何比较和查找两个直方图是否相同?
- excel - 使用python在excel中自动化手动分组过程
- c++ - cocos实验音频引擎如何制作audioID
- node.js - 如何重写 NodeJS CryptoJS 函数以便它们在 ReactJS web 中工作?
- r - 如何确保仅在使用 Shiny 按下操作按钮时触发操作
- java - 使用给定的单词列表重新创建给定字符串的方法数