reactjs - 如何让 Yup 执行多个自定义验证?
问题描述
我正在做一个 ReactJS 项目。我正在学习Yup
使用FormIk
. 以下代码工作正常:
const ValidationSchema = Yup.object().shape({
paymentCardName: Yup.string().required(s.validation.paymentCardName.required),
paymentCardNumber: Yup.string()
/*
.test(
"test-num",
"Requires 16 digits",
(value) => !isEmpty(value) && value.replace(/\s/g, "").length === 16
)
*/
.test(
"test-ctype",
"We do not accept this card type",
(value) => getCardType(value).length > 0
)
.required(),
但是,当我取消注释test-num
开发人员工具的那一刻,我抱怨了一个未捕获的承诺:
如何让 Yup 根据我检测到的验证失败给我一个不同的错误字符串?
解决方案
您可以使用addMethod方法创建两个像这样的自定义验证方法。
Yup.addMethod(Yup.string, "creditCardType", function (errorMessage) {
return this.test(`test-card-type`, errorMessage, function (value) {
const { path, createError } = this;
return (
getCardType(value).length > 0 ||
createError({ path, message: errorMessage })
);
});
});
Yup.addMethod(Yup.string, "creditCardLength", function (errorMessage) {
return this.test(`test-card-length`, errorMessage, function (value) {
const { path, createError } = this;
return (
(value && value.length === 16) ||
createError({ path, message: errorMessage })
);
});
});
const validationSchema = Yup.object().shape({
creditCard: Yup.string()
.creditCardType("We do not accept this card type")
.creditCardLength('Too short')
.required("Required"),
});
推荐阅读
- python - MYSQL,Python。数据库中表之间依赖关系的树形结构
- amazon-s3 - S3 中需要用于 EMR 或 Redshift 上的机器学习的压缩数据
- identityserver4 - Identity Server 4 - 用户身份验证 - 机密应用程序 - 多个客户端密码 - 一个 Client_ID
- angular - Angular - 如何为 mat-tab 中的不同选项卡创建单独的“ViewContainerRef”容器
- c# - SpeechRecognizer的Windows 10 iot核心语言安装
- java - 如何在 Java 中使用带有通用节点的循环双链表编写删除方法
- javascript - 为什么我的功能支持测试在语法错误发生之前没有运行?
- usb - USB 行为与预期不符
- freemarker - 如果是相同输出的两倍,我如何删除列表的某些部分?
- javascript - d3.js 条形图不显示条形