I am working with Joi validator and Node js and trying to assign the current date to an attribute using Joi, I have tried these two alternatives but neither one worked for me
createdAt: Joi.date().default(new Date(Date.now()))
and
createdAt: Joi.date().default(Joi.date().timestamp())
Is this feasible to do with Joi, if yes, would you please help me to figure it out?
Many thanks in advance
Joi.date()
needs a string date format
Joi.timestamp()
needs a number of milliseconds
Demo
const Joi = require('joi')
const schema = Joi.object({
createdTimeStamp: Joi.date().timestamp(),
createdDate: Joi.date()
})
const now = Date.now()
const nowDate = new Date(now)
const result = schema.validate(
{
createdTimeStamp: now,
createdDate: nowDate
})
console.log('Joi.date().timestamp(): ' + now)
console.log('Joi.date(): ' + nowDate)
console.log('result: ' + JSON.stringify(result, null, 4))
Result
$ node test.js
Joi.date().timestamp(): 1676893420897
Joi.date(): Mon Feb 20 2023 06:43:40 GMT-0500 (Eastern Standard Time)
result: {
"value": {
"createdTimeStamp": "2023-02-20T11:43:40.897Z",
"createdDate": "2023-02-20T11:43:40.897Z"
}
}