如何在YUP中选中三个复选框时进行验证?

时间:2019-02-25 10:13:49

标签: formik yup

我有三个复选框:

[*] option one
[*] option two
[*] option three

仅当所有三个都被选中时,有效状态。 所有其他状态均无效,并应显示错误消息。

如何用yup实现它?

我当前的实现无效。它仅验证单个复选框,而不是全部。

yup.object().shape({
  registerTerms: yup.boolean().oneOf([true], 'Must Accept Terms of Service'),
  registerCookie: yup.boolean().oneOf([true], 'Must Accept Cookie Policy'),
  registerPrivacy: yup.boolean().oneOf([true], 'Must Accept Privacy Policy'),
}),

1 个答案:

答案 0 :(得分:0)

您的架构定义看起来正确。

import * as yup from "yup";

const schema = yup.object().shape({
  registerTerms: yup.boolean().oneOf([true], "Must Accept Terms of Service"),
  registerCookie: yup.boolean().oneOf([true], "Must Accept Cookie Policy"),
  registerPrivacy: yup.boolean().oneOf([true], "Must Accept Privacy Policy")
});

const validInputObj = {
  registerTerms: true,
  registerCookie: true,
  registerPrivacy: true
};

const invalidInputObj = {
  registerTerms: true,
  registerCookie: true,
  registerPrivacy: false
};

schema.isValid(validInputObj).then(isValid => console.log(isValid));   // true
schema.isValid(invalidInputObj).then(isValid => console.log(isValid)); // false

我已经tested it out in codesandbox,而且似乎工作正常。