Yup/Formik min date does not include current date
Asked Answered
M

3

12

I have this schema in Yup that puts a minimum date constraint on the date field:

Yup.date()
   .required(strings.RequiredField(strings.Invoice_Label_DueDate))
   .min(new Date(), "Date cannot be in the past")

But if I select the current date, it still computes it to be in the past. Note that this doesn't happen when I do max(new Date(), ...). In this case, it includes all past dates upto and including the current date.

Edit: Here's an example of the problem https://codesandbox.io/s/jznz5vl7lw

Maurist answered 28/2, 2019 at 2:47 Comment(0)
A
9

You can also use:

const today = new Date();
today.setHours(0, 0, 0, 0)

then

.min(today, 'Date cannot be in the past')
Alienable answered 9/7, 2020 at 16:36 Comment(0)
G
2

If you want to set the minimum to be yesterday's date, you can declare a variable and set it to yesterday's date, for example (there are many other ways too):

const yesterday = new Date(Date.now() -86400000);

then:

.min(yesterday, "Date cannot be in the past")
Gyrostatics answered 18/5, 2020 at 14:1 Comment(0)
C
1

I am using this to validate card expiry. It can be manipulated, for normal date as well.

cardExpiry: Yup.string()
      .required("Card Expiry is required")
      .matches(/^(0[1-9]|1[0-2])\/\d{4}$/, "Invalid Card Expiry (MM/YYYY)")
      .test("cardExpiry", "Date cannot be in the past", function (value) {
        const today = new Date();
        const [expiryMonth, expiryYear] = value.split("/");
        const cardExpiryDate = new Date(
          parseInt(expiryYear),
          parseInt(expiryMonth) - 1
        );
        return cardExpiryDate >= today;
      })

Hope this will help someone.

Clarinda answered 4/8, 2023 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.