根据状态变量进行条件 Yup 验证

Ala*_*hil 6 reactjs yup react-hook-form

仅当给定变量的状态为 true 时,是否可以使用 Yup 解析器 RHF 有条件地验证文本字段。

我研究了很多但找不到例子。

谢谢

Asi*_*ora 5

用于Yup.when归档条件库验证。检查更多详细信息是的

例子:

您可以使用 Yup 条件

const validationSchema = Yup.object().shape({
  isCompany: Yup.boolean(),
  companyName: Yup.string().when('isCompany', {
    is: true,
    then: Yup.string().required('Field is required')
  }),
  companyAddress: Yup.string().when('isCompany', {
    is: (isCompany) => true,//just an e.g. you can return a function
    then: Yup.string().required('Field is required'),
    otherwise: Yup.string()
  }),
});
Run Code Online (Sandbox Code Playgroud)

并确保相应地更新您的表格。我希望你明白这一点。