基于另一个非必填字段的Yup验证

时间:2020-02-06 09:32:17

标签: reactjs react-bootstrap formik yup

我正在使用Formik和React-bootstrap在React中构建表单,并且正在使用Yup来验证表单。

我有2个字段,比如说FieldA和FieldB。如果FieldA不为空,则不需要FieldA,但需要FieldB。

FieldA是一个文本框,而FieldB是多选。我对FieldB的验证规则必须为:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        'index': [1, 2, 3,  4,  5,  6,   7,  8, 9],
        'value': [5, 6, 7, np.nan, 9, 3, 11, 34, 78]
    }
)

df_chunked = df[(df['index'] >= 1) & (df['index'] <= 5)]

print('df_chunked')
print(df_chunked)

df_result = df_chunked[(df_chunked['value'] < 10)]
# df_result = df_chunked[(df_chunked['value'] < 10) | (df_chunked['value'] == np.isnan(df_chunked['value']))]

print('df_result')
print(df_result)

2 个答案:

答案 0 :(得分:10)

尝试一下:

const schema = Yup.object().shape({
       FieldA: Yup.string(),
       FieldB: Yup.string()
        .when('FieldA', {
          is: (FieldA) => FieldA.length > 0,
          then: Yup.string()
            .required('Field is required')            
        })
    });

答案 1 :(得分:1)

使用here中提到的validate中的Formkit选项

const validate = values =>
  if (values.a > values.b){
    //return error message for assumed filed
    return {
      a: 'a is greater than b',
    };
  }

Formkit中:

<Formik
    initialValues={{
    a: 2,
    b: 1,
    }}
    validate={validate}