I'm using React-Datepicker inside a Formik form validated with Yup. To integrate React-Datepicker inside Formik I used the wrapper solution in this thread.
When a value is initially entered, .required()
gets checked, but any other validation does not get checked. So I'm not getting my StartDate later than today
validation right away. These other validations do get triggered if I re-enter the control a second time and exit it. So the only initial validation error that happens immediately is .required()
, but for any other errors I need to re-touch the control. Are there any solutions to this?
EDIT: I noticed that Formik's .touched
does not get set on the 1st DatePicker input. It only gets set on subsequent touches/inputs.
Yup
startDate: yup.date().nullable().required('Start Date is required')
.min(new Date(), 'Start Date must be later than today'),
DatePicker Wrapper -see this thread - credit to ToolmakerStever
I tried adding onCalendarClose
to force re-validation per this DatePicker issue report, and it indeed may be happening, but this could also be a Yup Schema issue -- I'm not sure.
const { setFieldValue, validateField, values, handleBlur } = useFormikContext();
return (
<DatePicker
{...field}
{...props}
showMonthDropdown
showYearDropdown
selected={(field.value && new Date(field.value)) || null}
onChange={val => {
setFieldValue(field.name, val);
}}
onCalendarClose={val => {
// Force-validate onCalendarClose to avoid any potential DatePicker Blur issues
// Didn't help
validateField(props.name);
}}
onBlur={e => {
// Call Formik's handleBlur
// Didn't help
handleBlur(e);
}}
/>
)