Yudi Krisnandi
Yudi Krisnandi

Reputation: 485

How to create custom validation in a field that need value from another field using formik and yup

I use formik and yup to handle form validation in my app.

I have 2 field that related to each other, let's say field 'date' and field 'time'.

I want to make a custom validation in field 'time' to check whether the time of the day has passed or not based on value from field 'date'

For example, today is 26 Feb 2021 and 08.00 AM, so that users cannot choose a time below 8 o'clock.

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

Upvotes: 2

Views: 1908

Answers (1)

Yudi Krisnandi
Yudi Krisnandi

Reputation: 485

I solve it by using .when method.

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>

Upvotes: 1

Related Questions