首页 > 解决方案 > 是的,条件验证

问题描述

如何实现条件,例如 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 的值?

标签: javascriptreactjsformsformikyup

解决方案


我不确定这是正确的方法,但我正在使用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;
})

推荐阅读