I am creating a simple form with date validation in React, Formik and Yup.
As you can see below, there are only two fields: datePurchase
and dateSale
. I set min
and max
parameters for both and I set them as required:
<Formik
initialValues={{
datePurchase: '',
dateSale: '',
}}
validationSchema={object()
.shape({
datePurchase: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
dateSale: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
})}
>
{({
values, handleChange, handleBlur,
}) => (
<Form>
<input
name="datePurchase"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.datePurchase}
/>
<input
name="dateSale"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.dateSale}
/>
</Form>
)}
</Formik>
Then, I realized that datePurchase
must be earlier than dateSale
.
How to implement such condition using validationSchema()
with Yup? Is that even possible?
I tried to use when()
method with is:
and then:
params from Yup documentation, but to no avail.
I am creating a simple form with date validation in React, Formik and Yup.
As you can see below, there are only two fields: datePurchase
and dateSale
. I set min
and max
parameters for both and I set them as required:
<Formik
initialValues={{
datePurchase: '',
dateSale: '',
}}
validationSchema={object()
.shape({
datePurchase: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
dateSale: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
})}
>
{({
values, handleChange, handleBlur,
}) => (
<Form>
<input
name="datePurchase"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.datePurchase}
/>
<input
name="dateSale"
type="date"
onChange={handleChange}
onBlur={handleBlur}
value={values.dateSale}
/>
</Form>
)}
</Formik>
Then, I realized that datePurchase
must be earlier than dateSale
.
How to implement such condition using validationSchema()
with Yup? Is that even possible?
I tried to use when()
method with is:
and then:
params from Yup documentation, but to no avail.
1 Answer
Reset to default 12Yup.ref allows you to reference other siblings - https://github./jquense/yup#yuprefpath-string-options--contextprefix-string--ref
Try giving this a go:
validationSchema={object()
.shape({
datePurchase: date()
.min(Yup.ref('dateSale')
.max(new Date())
.required(),
dateSale: date()
.min(new Date('01-01-2019'))
.max(new Date())
.required(),
})}