Search code examples
datejoi

Joi validate Dates for range and exact date


I am working on a date input for interfacing with stripe. When testing we need to allow the specific date of 01/01/1901 but for all other cases we need to ensure that the birthdate is 18 or more years ago but not more than 100 years ago. This last part I can easily do with the following joi command

Joi.date().format("MM/DD/YYYY").raw().required().max(<a specific date value>).min(<Another Date Value>).messages(errorMessages)

My question is, for the sake of testing we need to allow specific dates to pass validation and I'm wondering if there is a way to have joi validate dates between a range or dates that are exactly equal to

thanks for any advice and help.


Solution

  • Yes. This can be achieved using any.alternatives() and any.valid().

    The following will allow your range rule plus a list of arbitrary dates ['01/01/1901', '12/12/2020']

    Joi.object().keys({
        date: Joi.alternatives(
            Joi.date().format("MM/DD/YYYY").raw().required().max(<a specific date value>).min(<Another Date Value>).messages(errorMessages),
            Joi.any().valid('01/01/1901', '12/12/2020')
        )
    })