首页 > 解决方案 > 根据状态变量进行条件 Yup 验证

问题描述

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

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

谢谢

标签: reactjsreact-hook-formyup

解决方案


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

例子:

您可以使用是的条件

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()
  }),
});

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


推荐阅读