Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i validate two hours with Yup?

I have a validation schema for my Formik Form on React Native using Yup. There are two fields (start_time and end_time) and i want to compare if start_time is after end_time and thrown a message to user.

I read about mixed.when and tried to figure out a solution with that, but i'm blocked with it.

const isSameOrAfterTime = (startTime, endTime) =>
  moment(startTime, HOUR_MINUTE_SECONDS_MASK).isSameOrAfter(endTime);

// example - data
// start_time: 08:00:25
// end_time: 10:23:42

start_time: Yup.string().when(['start_time', 'end_time'], {
    is: (startTime, endTime) => isSameOrAfterTime(startTime, endTime),
    then: Yup.string() // ???
    otherwise: // ????
  }),

I want to thrown a message when the start_time is after end_time

Edit rough-currying-t9n88

like image 886
Maurício Reatto Duarte Avatar asked Jan 26 '23 04:01

Maurício Reatto Duarte


1 Answers

Use yup.test instead.

https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema


const SignupSchema = Yup.object().shape({
  // (end_time, screma, self)
  start_time: Yup.string()
  .test(
    'not empty',
    'Start time cant be empty',
    function(value) {
      return !!value;
    }
  )
  .test(
    "start_time_test",
    "Start time must be before end time",
    function(value) {
      const { end_time } = this.parent;
      return isSameOrBefore(value, end_time);
    }
  ),
  end_time: Yup.string()
});

const isSameOrBefore = (startTime, endTime) => {
  return moment(startTime, 'HH:mm').isSameOrBefore(moment(endTime, 'HH:mm'));
}

https://codesandbox.io/s/awesome-johnson-vdueg

like image 131
Andrei Calazans Avatar answered Jan 29 '23 21:01

Andrei Calazans