I have made a validation middleware whose code is given below like this.
export const validateMiddleware = async (req, res, next) => {
const validateExpression = Joi.object()
.keys({
'startDate': Joi.string()
.optional()
.allow(''),
'endDate': Joi.string()
.optional()
.allow('')
});
const {
error
} = validateExpression.validate(req.query, {
'convert': false,
'abortEarly': false
});
if (error) {
// Return response regarding that error.
} else {
next();
}
};
I need to validate that startDate and endDate fields should be string of format YYYY-MM-DD also need to validate that startDate < endDate date value. How can I achieve this using Joi in Node JS ?.
I think this code will solve your problem:
const validateExpression = Joi.object()
.keys({
'startDate': Joi.date()
.format("YYYY-MM-DD")
.optional()
.allow(''),
'endDate': Joi.date()
.format("YYYY-MM-DD")
.optional()
.allow('')
.min(Joi.ref('startDate'))
});
Try this:
const Joi = require("joi").extend(require("@joi/date"));
export const validateMiddleware = async (req, res, next) => {
const validateExpression = Joi.object()
.keys({
'startDate': Joi.date()
.format("YYYY-MM-DD")
.strict(false) // required if 'convert' option is set to "false"
.optional()
.allow(''),
'endDate': Joi.date()
.format("YYYY-MM-DD")
.greater(Joi.ref("startDate")) // checks if it is greater than startDate, throws error if now.
.strict(false) // can be omitted if 'convert' option is set to "true"
.optional()
.allow('')
});
const {
error
} = validateExpression.validate(req.query, {
'convert': false,
'abortEarly': false
});
if (error) {
// Return response regarding that error.
} else {
next();
}
};
DO NOT forget to call strict(false). Otherwise passing date as string won't work, since you have 'convert': false. Or alternatively, you can set 'convert': true (which is the default value anyway) and you won't need to call string(false) on startDate and endDate.