Search code examples
javascriptnode.jsvalidationbackendjoi

Limit range from start to end in Joi validation


Add Joi validation in nodeJs to limit endDate to be no more than 3 years after startDate.

Example : startDate 2024-03-29 , max endDate should be: 2027-03-29.

I tried:

const maxEndDate = Joi.ref('startDate', {
  adjust: startDate => startDate.getTime() + 1000 * 60 * 60 * 24 * (365 * 3)
});

const validate =
  query: {
    endDate: Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).raw().required(),
  }

and

const maxEndDate = Joi.ref('startDate', { adjust: ['+3 years'] })

but looks like it doesn't add 3 years, it only takes startDate as ref and gives error:

"message": "\"endDate\" must be less than or equal to \"Fri Mar 29 2024 03:00:00 GMT+0300\"

Solution

  • There is a corrections needed.

    1. When defining the validation schema, you should use Joi.object() to wrap the query object.

    You can try:

    const maxEndDate = Joi.ref('startDate', {
      adjust: startDate => startDate.getTime() + (1000 * 60 * 60 * 24 * 365 * 3) 
    });
    

    Instead of :

    const maxEndDate = Joi.ref('startDate', {
      adjust: startDate => startDate.getTime() + 1000 * 60 * 60 * 24 * (365 * 3)
    });
    

    And

    const validate = Joi.object({
      query: Joi.object({
        startDate: Joi.date().format(DATE_FORMAT).utc().required(),
        endDate: Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).required(),
      })
    });
    

    Instead of:

    const validate =
          query: {
            endDate: 
    Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).raw().required(),
          }