Yup validation – Date must be greater than other date

by admin
yup-image

Yup (found here) can be awesome, it can also be tricky sometimes. For example, conditional validation based on another field may be difficult.

I’ve got an example right here where I have an endDate that must be later than the startDate. A pretty regular occurence right? This is how you can validate that with Yup.

  const validationSchema = Yup.object().shape({
    startDate: Yup.date().nullable().label('Start date').required(),
    endDate: Yup.date()
      .nullable()
      .test('is-before-endDate', 'Enddate must be after start date', function (endDate) {
        const startDate = this.resolve(Yup.ref('startDate'))
        if (!startDate || !endDate) return true

        return startDate < endDate
      })
  })

This code snippet validates that the endDate is after the startDate. You may notice that I have added .nullable() to the start date. In my case that is because a user is able to clear the startdate. If you don’t add Nullable(), the validator will crash.

Related Posts

Leave a Comment