Yup中的条件验证

时间:2018-07-24 08:36:17

标签: javascript reactjs forms formik yup

如何实现像1个字段的值这样的条件应始终大于另一个字段的值。

这是我的模式

   value: Yup.number().required(''),
   value2: Yup.number().when('value',{
     is: (val) => something here
    then: Yup.number().required('Required').positive('value should be positive'),
    otherwise: Yup.number()
  })

我想检查value2始终是> value。 在when条件下如何访问value2的值?

4 个答案:

答案 0 :(得分:2)

如果要在两个字段之间比较大于条件,请尝试此操作

import * as Yup from 'yup';
value: Yup.number().required(''),
value2: Yup.number().required()
   .moreThan(
    Yup.ref('value'),
    'Should be more than value2'
    )

答案 1 :(得分:1)

我不确定这是正确的方法,但是我正在使用test

赞:

yourField: Yup.string().test('should-be-greather-than-yourField2', 'Should be greather than yourfield 2', function(value) {
  const otherFieldValue = this.parent.yourField2

  if (!otherFieldValue) {
    return true;
  }
  return value > otherFieldValue;
})

答案 2 :(得分:0)

我不确定,但是尝试is: (val) => Yup.number().moreThan(val)

答案 3 :(得分:-1)

我正在验证电子邮件和手机号码的相同字段,以便用户可以验证两者是相同的字段。

  username: yup
      .string().when({
        is : value =>isNaN(value),
        then: yup.string().required('email/mobileno is required') .matches( Regex.EMAIL_REGX,
          'Invalid email',
        ),
        otherwise: yup.string()
        .matches(Regex.PHONENO_REGX, StringUtils.phoneNo)
      }),