[英]Yup validation - check if value doesn't match other field
Hi I am trying to find a way to compare 2 fields and validate only if they are not equal.您好我正在尝试找到一种方法来比较 2 个字段并仅在它们不相等时才进行验证。
This is the only idea I was able to come up with but it doesn't work:这是我能想到的唯一想法,但行不通:
yup
.number()
.required()
.notOneOf(
[FormField.houseHoldMembers as any],
'error message',
),
You can compare the two values and validate only if they are not equal like this:您可以比较这两个值并仅在它们不相等时进行验证,如下所示:
const mySchema = yup.object({
text1: yup.number().required(),
text2: yup
.number()
.required()
.when(["text1"], (text1, schema) => {
console.log(schema);
return schema.notOneOf([text1], "the two values should not be equal");
})
});
You can take a look at this sandbox for a live working example of this solution.您可以查看此沙箱,了解此解决方案的实时工作示例。
Shorted:短路:
const schema = yup.object({
field1: yup.number().required(),
field2: yup
.number()
.required()
.notOneOf([yup.ref('field1'), null], 'The two values should not be equal'),
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.