2

我有三个复选框:

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

只有当所有三个都被检查时才有效。所有其他状态均无效,应显示错误消息。

如何用是的来实现它?

我当前的实现不起作用。它只验证单个复选框,而不是全部。

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'),
}),
4

1 回答 1

3

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

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

我已经在代码沙箱中对其进行了测试,它似乎工作正常。

于 2019-02-26T03:11:55.913 回答