How To Use Yup To validate Date: Start date and End Date

How To Use Yup To validate Date: Start date and End Date

Table of contents

No heading

No headings in the article.

Yup is a JavaScript schema validation library that allows you to validate data structures against a schema. It is commonly used to validate input in React.js applications.

With Yup, you can define a schema that specifies the structure and data types of your data, as well as any validation rules. You can then use this schema to validate user input, ensuring that it meets your specified requirements. Yup provides a fluent, chainable API that makes it easy to define complex validation rules.

To use Yup in a React.js application, you typically define a validation schema and use it to validate input data in your form components. Yup integrates well with popular form libraries like Formik and react-hook-form, allowing you to easily incorporate validation into your form workflow.

Overall, Yup is a powerful tool for validating data in JavaScript applications and can help ensure the accuracy and integrity of your data.

To validate that the end date is not earlier than the start date using Yup validation, you can use the yup.date() method to define both the start and end dates as date values.

Then, you can use the yup.date().min() method to set the minimum allowed value for the end date, which should be the value of the start date. This will ensure that the end date is not earlier than the start date.

Here's an example code snippet that demonstrates how to achieve this:

  1. Using plain JavaScript objects:
import * as yup from 'yup';

const schema = yup.object().shape({
  startDate: yup.date().required(),
  endDate: yup
    .date()
    .required()
    .min(yup.ref('startDate'), 'End date cannot be earlier than start date'),
});

const data = {
  startDate: new Date('2022-01-01'),
  endDate: new Date('2021-12-31'),
};

schema.validate(data).catch((err) => console.error(err.message));

In the above example, the endDate field is defined using the yup.date() method, followed by the .min() method which sets the minimum value of the field to be the value of the startDate field. The error message passed as the second parameter to the .min() method will be displayed if the validation fails.

When validating the data using the schema.validate() method, an error will be thrown with the message "End date cannot be earlier than start date" because the endDate is earlier than the startDate.

  1. Using formik form:
const validationSchema = Yup.object().shape({
  startDate: Yup.date().required(),
  endDate: Yup.date()
    .required()
    .min(Yup.ref('startDate'), 'End date cannot be earlier than start date')
});

<Formik
  initialValues={{
    startDate: '',
    endDate: ''
  }}
  validationSchema={validationSchema}
  onSubmit={(values) => {
    // handle form submission
  }}
>
  {({
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting
  }) => (
    <form onSubmit={handleSubmit}>
      <input
        type="date"
        name="startDate"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.startDate}
      />
      {touched.startDate && errors.startDate && (
        <div>{errors.startDate}</div>
      )}
      <input
        type="date"
        name="endDate"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.endDate}
      />
      {touched.endDate && errors.endDate && (
        <div>{errors.endDate}</div>
      )}
      <button type="submit" disabled={isSubmitting}>
        Submit
      </button>
    </form>
  )}
</Formik>
  1. Using React class components:
 class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: '',
      endDate: ''
    };
  }

  validationSchema = Yup.object().shape({
    startDate: Yup.date().required(),
    endDate: Yup.date()
      .required()
      .min(Yup.ref('startDate'), 'End date cannot be earlier than start date')
  });

  handleChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = () => {
    // handle form submission
  };

  render() {
    return (
      <Formik
        initialValues={this.state}
        validationSchema={this.validationSchema}
        onSubmit={this.handleSubmit}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting
        }) => (
          <form onSubmit={handleSubmit}>
            <input
              type="date"
              name="startDate"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.startDate}
            />
            {touched.startDate && errors.startDate && (
              <div>{errors.startDate}</div>
            )}
            <input
              type="date"
              name="endDate"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.endDate}
            />
            {touched.endDate && errors.endDate && (
              <div>{errors.endDate}</div>
            )}
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </form>
        )}
      </Formik>
    );
  }
}

These examples use the .min() method of Yup to

In conclusion, Yup validation provides an easy way to validate that an end date is not earlier than a start date in JavaScript. By using the .min() method of Yup to set the minimum allowed value for the end date, which should be the value of the start date, we can ensure that the end date is not earlier than the start date. Yup validation can be used with plain JavaScript objects, formik forms, or React class components. Overall, Yup validation is a powerful and versatile tool for validating data in JavaScript applications.