get current value on yup when condition

Viewed 103

I have two date fields, start date, and end date. I would like to know how to set up a validation not to accept the start date to be higher than the end date and vice-versa.

Reading the yup documentation I saw the when condition, but it just gets values from other fields!

Date fileds

import { date, object } from 'yup';

export const yupSchema = object({
  startAt: date().typeError('Invalid date').nullable(),
  endAt: date().typeError('Invalid date').nullable(),
});

1 Answers

You can try this validation to compare these two dates,

import * as Yup from 'yup';

export const yupSchema = Yup.object().shape({
  startAt: Yup.date().nullable(true).required('Start At is
  required.'),
  endAt: Yup.date()
    .nullable(true)
    .when(
      'startAt',
      (startAt, schema) =>
        startAt && schema.min(startAt, 'Start At should be later than End At')
    )
});
Related