I have a json to be validated by joi. It contains two optional date fields: start & end. So I want to compare them to ensure start date is older than end date.
I know how to do this if they both were mandatory fields:
end: Joi.date().iso().min(Joi.ref('start'))
The problem is they are optional fields so it fails when there is end date but no start date:
"cause": "[{\"end\":\"\\\"end\\\" date references \\\"ref:start\\\" which must have a valid date format\"}]"
How can I compare two dates just in case both of them exists?
Thanks!
Edit: I've just found a way:
.min(
Joi.ref("start", {
adjust: (value) => (value ? value : new Date(1970, 1, 1)),
})
),
This code will compare end date with 1/1/1970 in case start date doesn't exists.
Now, I'm curious if there is another way to do this in a better or cleaner way.