基于另一个字段的值,要求填写特定字段 - Formik,Yup

6

我有一个React Formik表单,其中有一个选择字段,假设该字段有值A、B、C、D、E、F。

现在假设另一个字段ChooseSubType只出现在我选择B或D时,并且此字段仅在显示之后成为必填字段而不是之前。

现在,我该如何让它工作?

以下是第一个字段即选择字段的代码:

chooseAlphabet: Yup.string().required('field required'),
chooseSubType : Yup.string().when('chooseAlphabet',
('chooseAlphabet',schema)=>{
   console.log('value business : ',chooseAlphabet);
   if(chooseAlphabet === "B"||"D"){
     return schema;
   }else{
     return schema.required('field required');
   }
  }),

但是这段代码没有生效。

现在,我需要做哪些更改才能使它按照我的意愿工作?


你是否在收到验证错误或chooseSubType没有出现? - Snekse
3个回答

9
我知道有点晚了,但你可以试试这个。
chooseSubType: yup.string().when('chooseAlphabet', {
  is: 'B',
  then: schema => schema,
  otherwise: yup.string().when('type', {
    is: 'D',
    then: yup.string().required('field required.')
  })
})

这个示例中的 schema => schema, 是什么意思?有相关文档链接吗? - Gel
@Gel 这是一个 yup 模式,链接到文档 https://github.com/jquense/yup#schemawhenkeys-string--string-builder-object--values-any-schema--schema-schema - Omkar Gokhale

4

你可以使用相同的代码,只需要进行改进,需要添加内容,请查看下面的代码。

chooseAlphabet: Yup.string().required('field required'),
chooseSubType : Yup.string().when('chooseAlphabet',
(chooseAlphabet,schema)=>{
    console.log('value business : ',chooseAlphabet);
    if(chooseAlphabet === "B"||"D"){
       return schema;
    }else{
       return schema.required('field required');
    }
}),

2

对于您的第二个参数,模式未定义。

 chooseAlphabet: Yup.string().required('field required'),
        chooseSubType : Yup.string().when('chooseAlphabet',
        (chooseAlphabetValue)=>{
           console.log('value business : ',chooseAlphabetValue);
           if(chooseAlphabetValue=== "B"||"D"){
             return Yup.string();
           }else{
             return Yup.string().required('field required');
           }
          }),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接