6

Validate the date field to be greater than x days from now.

Right now I have this snippet that checks if the date is greater than now.

planned_date: Joi.date().greater('now').required()

But I want to validate that the planned_date is at least 2 days more than now. This could be possible combining with moment.js, but couldn't get it working.

6
  • Can you do something like this? const dateLater = moment.tz(new Date(), '').unix() + 48 * 60 * 60 This will give you date 2 days later at same time and then later on you can do this planned_date: Joi.date().greater(dateLater).required() Commented Apr 23, 2021 at 6:57
  • @reD Here I'm just concerned that the dateLater might become a hard value rather than being evaluated every time. I'll try if this works. Commented Apr 23, 2021 at 7:02
  • Also, something in-built with JOI would be better. Commented Apr 23, 2021 at 7:03
  • 3
    Ahh, actually idk if there is anything built on joi but this will definitely work. planned_date: Joi.date().required().greater(Date.now() + 48 * 60 * 60 * 1000) Commented Apr 23, 2021 at 7:07
  • @rED Your above comment with 'Date.now() + 48 * 60 * 60 * 1000' works well for me. I think you can add it as an answer as well. Commented Apr 24, 2021 at 18:00

1 Answer 1

8

This will check for date greater than 2 days, what we are doing is using Date.now() to get current time stamp in epoch later adding 2 days time in epoch to get the validation we wanted.

planned_date: Joi.date().required().greater(Date.now() + 48 * 60 * 60 * 1000)

1
  • Is the right way to do it when validating request parameters? Because Date.now will be the date that the server opened(or sth like that). I was having this issue and a custom validator helped instead of this answer. Therefore, i was taking the Date.now in every request inside the custom validator.
    – Cache
    Commented Aug 2, 2023 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.