如何使用 formik 和 yup 在需要来自另一个字段的值的字段中创建自定义验证

问题描述

我使用 formik 和 yup 在我的应用中处理表单验证。

我有 2 个相互关联的字段,比如说字段“日期”和字段“时间”。

我想在字段 'time' 中进行自定义验证,以根据字段 'date' 中的值检查一天中的时间是否已经过去

例如,今天是 2021 年 2 月 26 日上午 08 点,因此用户无法选择 8 点以下的时间。

date: string().required('date required'),time: string()
  .required('time is require')
  .matches(myCustomregex)

解决方法

我使用 .when 方法解决。

date: string().required('date required'),time: string()
  .required('time is require')
  .matches(myCustomRegex)
  .when('date',{
    .is: data => date && date moment(new Date(),'x').format('DD/MM/YYYY') === moment(new Date(date),'x').format('DD/MM/YYYY')
    .then: String().test(
      'time','Start Time must not  be less than the current time',value => {
        if(value){
          const currentHour = new Date().getHours();
          const currentMinute = new Date().getMinutes();
          const userPickHour = parseInt(value.split(':')[0],10)
          const userPickMinute = parseInt(value.split(':')[1],10);
          if(userPickHour < currentHour){
            return false;
          }else if(userPickHour === currentHour && userPickMinute <= currentMinute){
            return false;
          }else {
            return true;
          }
        }
        return true;
      }
    )
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...