Closed NitinHsharma closed 5 years ago
Be aware that .greater(new Date())
would only have one value and that is the time you started your server at. .greater(new Date())
is not evaluated at every request. You'd better use .greater('now')
instead for that purpose. See: https://github.com/hapijs/joi/blob/v15.0.3/API.md#dategreaterdate
Thanks @Nargonath Can you also help me to understand how to add buffer into a date, Like I want to date should be greater than from date and difference between them should not be more than 14days
Alright we discussed your issue on the Slack channel, kudos to @AdriVanHoudt for his vanilla joi
suggestion. Here my solution to your problem based on his suggestion:
Joi.object({
fourteenDaysInterval: Joi.date()
.default(
context =>
moment(context.fromDate)
.add(14, "days")
.toDate(),
"14 days after fromDate"
)
.forbidden(),
fromDate: Joi.date()
.format("DD/MM/YYYY")
.greater("now")
.required(),
toDate: Joi.date()
.format("DD/MM/YYYY")
.greater(Joi.ref("fromDate"))
.less(Joi.ref("fourteenDaysInterval"))
.required()
});
The main thing to grasp here is that we use a new property fourteenDaysInterval
to store a date whose value is fromDate
+ 14 days. We use .forbidden()
so that value cannot be send to the server. I've used moment
for easier Date
manipulation. We just need then to reference that property in the .less()
method.
Champ :man_dancing:
Thank you so much the help
You're welcome. 😉
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.
I have an input object like { fromDate: 'DD-MM-YYYY', toDate: 'DD-MM-YYYY'} I have to check below three validation 1) Proper format (DD-MM-YYYY) 2) fromDate should be greater than today 3) toDate should be greater than fromDate and difference between fromDate and toDate should not be greater than 14 days.
my JOI schema is
const BaseJoi = require('@hapi/joi'); const Extension = require('@hapi/joi-date'); const Joi = BaseJoi.extend(Extension);
const transactionModel = Joi.object().keys({ fromDate: Joi.date().format('DD/MM/YYYY').greater(new Date()).required(), toDate: Joi.date().format('DD/MM/YYYY').greater(Joi.ref('fromDate')).less(Joi.ref('fromDate')).required(), });
How to add 14 days to fromDate for checking less condition in the above schema?