0
votes

I'm using yup validationSchema for Formik, however, when I'm trying to validate date, it doesn't work, validation for all other fields work correctly. What I'm doing wrong?

 const formSchema = yup.object({
     startsAt: yup.date().label('startsAt').required("Required").min(new Date(Date.now() -86400000), "Date cannot be in the past"),
     endsAt: yup.date().label('endsAt').required("Required").min(yup.ref('startsAt'),"End date can't be less than start date")
  })

Here is my DatePickers:

import { DatePicker } from 'formik-material-ui-pickers'
import { Formik, Field, Form} from 'formik'

  <Formik 
    validationSchema={formSchema}
   >
    <Form>
    <Field
          component={DatePicker}
          format="MM/DD/YYYY"
          inputVariant="outlined"
          name="startsAt"
          label="Start Date"
          className={classes.dtPicker}
        />
        <Field
          component={DatePicker}
          format="MM/DD/YYYY"
          inputVariant="outlined"
          name="endsAt"
          label="End Date"
          className={classes.dtPicker}
        />
      </Form>
    </Formik>  
1

1 Answers

1
votes

Instead of:

startsAt: yup.date().label('startsAt').required("Required").min(new 
Date(Date.now() -86400000), "Date cannot be in the past"),
     

try:

import {parse, isDate} from 'date-fns';
const parseDateString = (value, originalValue) =>
  isDate(originalValue) ? originalValue : parse(originalValue);


startsAt: yup.date().label('startsAt').required("Required")
.transform(parseDateString)
.min(
      new Date().setHours(0, 0, 0, 0),
      'Date cannot be in the past'
    ),