Joi Validation - Compare to dates from POST

tdotcspot picture tdotcspot · Nov 9, 2015 · Viewed 13.6k times · Source

I'm currently using Joi in HapiJS / NodeJS to validate data. One POST in particular has two ISO dates (start date and end date) that are passed to the route and validated to make sure they are ISO dates.

{
    method: 'POST',
    path: '/api/calendar',
    handler: calendar.getInfo,
    config: {
        validate: {
            payload: {
                start: Joi.date().iso(),
                end: Joi.date().iso()
            }
        }
    }
}

I know I can pass those two dates and do some validation in the controller to make sure the start date is before the end date (ie, The start date cannot be Feb, and end date is Jan).

My question is if there is a way for Joi to determine this instead and error out? Let me know if more information is needed.

Thanks! T

Answer

Gergo Erdosi picture Gergo Erdosi · Nov 9, 2015

You can use Joi.ref() to reference other values:

end: Joi.date().iso().min(Joi.ref('start'))