Joi unix timestamp set max value

4.4k views Asked by At

I'm using Joi package to validate a timestamp field but How can I set a max() value on it, I want the input timestamp to be less than current time stamp

var schema = Joi.object().keys({
    t: Joi.date().timestamp('unix').max(moment().unix()),
})

but I get the error that:

child "t" fails because ["t" must be less than or equal to "Sun Jan 18 1970 07:35:17 GMT+0330 (IRST)"]

I'm sure that the moment().unix() returns the current timestamp, but here it is casted to string.

2

There are 2 answers

1
Amin Fazlali On BEST ANSWER

It seems that max() and min() functions can do the trick but they only work if the threshold is specified in milliseconds.

t: Joi.date().timestamp('unix')
.max(moment().unix() * 1000)
.min(moment().subtract('42', 'weeks').unix() * 1000),
0
Cuthbert On

It doesn't look like Joi.date().max() accepts unix timestamps properly despite being able to specify in your schema that a unix timestamp is expected for incoming values.

If you need to use the current date in your schema you can pass the string 'now' instead of using the date. Or just make sure you enter the current date in format that .max() expects. I tried this using milliseconds and it seems to work as expected. I think Joi is using the default Date constructor under the hood to construct dates to compare which expects milliseconds.

var schema = Joi.object().keys({
    t: Joi.date().timestamp('unix').max(moment().unix() * 1000)
});

From the docs on date.max()

Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, allowing to explicitly ensure a date is either in the past or in the future.