是的验证 - 检查值是否与其他字段不匹配



嗨,我正试图找到一种方法来比较两个字段,并仅在它们不相等时进行验证。

这是我唯一能想到的想法,但它不起作用:

yup
.number()
.required()
.notOneOf(
[FormField.houseHoldMembers as any],
'error message',
),

您可以比较这两个值,只有当它们不相等时才进行验证,如下所示:

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

你可以看看这个沙箱,看看这个解决方案的实际工作示例。

短路:

const schema = yup.object({
field1: yup.number().required(),
field2: yup
.number()
.required()
.notOneOf([yup.ref('field1'), null], 'The two values should not be equal'),
});

最新更新