【问题标题】:Conditionally Validation in Yup是的,条件验证
【发布时间】:2018-12-31 19:26:04
【问题描述】:

如何实现条件,比如一个字段的值应该总是大于另一个字段的值。

这是我的架构

   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 是否始终为 > 值。 如何在when条件下访问value2的值?

【问题讨论】:

    标签: javascript reactjs forms formik yup


    【解决方案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】:

      如果您想比较两个字段之间的超过条件,请尝试此操作

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

      【讨论】:

      • 如果第一个值不是必填字段,这将失败
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        我正在验证电子邮件和手机号码的相同字段,因此用户可以验证这两个字段是否相同。

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

        【讨论】:

          猜你喜欢
          • 2021-08-18
          • 1970-01-01
          • 2021-06-24
          • 2021-08-24
          • 2011-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-21
          相关资源
          最近更新 更多