Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current value on yup when condition

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(),
});

like image 859
niltonxp Avatar asked Oct 20 '25 20:10

niltonxp


1 Answers

You can utilize ref's - no when required.

Example code:

const validationSchema = Yup.object().shape({
    arrivalDate: Yup.date().required(),
    departureDate: Yup.date().required().min(Yup.ref('arrivalDate'), 'Departure date must be after arrival date')})

Last time I checked when does not receive the current value, only the value of the sibling field you're checking. See this issue on Github where someone asked this exact question.

like image 86
efru Avatar answered Oct 22 '25 09:10

efru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!