DEV Community

Cover image for Dates validation with Formik and Yup in React & React Native
Sergey Panarin
Sergey Panarin

Posted on • Updated on

Dates validation with Formik and Yup in React & React Native

Hi there!
Sometimes you need to validate dates in your React&React Native forms created with Formik and Yup. Classic example will be some start date and end date, where the simple rule will be to check that the latter goes after the former.

It was quite hard to find something that worked well, basically because standard JavaScript Date() object cannot parse all the string formats quite well.

So here is the solution that validates:

  • date format MM/DD/YYY with regular expression
  • that end date goes after the start date using moment and yup test function

Validation demo

Dates validation demo

Dates validation demo

Validation schema code

Here is Yup validation schema that you can use in your projects:

// form validation
import { Formik, Field } from "formik";
import * as yup from "yup";
import moment from "moment";

const datesValidationSchema = yup.object().shape({
  dateStart: yup
    .string()
    .required("Start date is required")
    .matches(
      /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/,
      "Date must be in MM/DD/YYYY format"
    ),
  dateEnd: yup
    .string()
    .matches(
      /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/,
      "Date must be in MM/DD/YYYY format"
    )
    .test(
      "dates-test",
      "End date should be after start date",
      (value, context) => {
        let startDate = moment(context.parent.dateStart, "MM/DD/YYYY").toDate();
        let endDate = moment(value, "MM/DD/YYYY").toDate();
        return endDate > startDate;
      }
    )
    .required("End date is required"),
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)