Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi Validation - Compare to dates from POST

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

like image 290
tdotcspot Avatar asked Nov 09 '15 18:11

tdotcspot


2 Answers

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

end: Joi.date().iso().min(Joi.ref('start'))
like image 70
Gergo Erdosi Avatar answered Nov 08 '22 16:11

Gergo Erdosi


You can use to compare two dates Like

 const Joi = require('joi');

const messagesUpdateObj = {
    startTime: Joi.date().iso().required(),
    endTime : Joi.date().iso().greater(Joi.ref('startTime')).required()
  };
let schema =  Joi.object().keys(messagesUpdateObj);
console.log(Joi.validate({startTime : '2018-08-28T11:46:30.120',endTime : '2018-08-29T11:46:30.120'}, schema));
like image 29
IftekharDani Avatar answered Nov 08 '22 14:11

IftekharDani