JOI validation would not allow Date to be null or empty string

Viewed 30

I have a use case where I need to send two dates from the frontend to a route and should be able to allow user to enter no dates at all if required.

However, when I try to send a request without making any changes to the date field I am getting a schema validation error.

I am doing a conditional check at the very top and if there is undefined being passed from the frontend, I am explicitly setting it to be null and the validation for DATE allows null values.

However, I still am getting a validation error. Can anyone please help me with this ?

export const updateProductsValidation = (req, res, next) => {
try {
    req.body.saleEndDate === undefined ? null : req.body.saleEndDate;
    req.body.saleStartDate === undefined ? null : req.body.saleStartDate;

    const schema = Joi.object({
        _id: SHORTSTR.required(),
        catId: SHORTSTR.required(),
        status: SHORTSTR.required(),
        name: SHORTSTR.required(),
        description: LONGSTR.required(),
        quantity: QUANTITY.required(),
        price: PRICE.required(),
        salePrice: PRICE,
        saleEndDate: DATE.allow(null).allow(''), //DATE = Joi.date();
        saleStartDate: DATE.allow(null).allow(''),
        images: LONGSTR.allow(null).allow(''),
        thumbnailImage: SHORTSTR,
        imageToDelete: LONGSTR.allow(null).allow(''),
    });
    validator(schema, req, res, next);
} catch (error) {
    next(error);
}};

Validator function :

export const validator = (schema, req, res, next) => {
    const { value, error } = schema.validate(req.body);
    if (error) {
        error.status = 200;
        return next(error);
    }
    next();
};

The DATE is a variable that has Joi.date() assigned to it.

0 Answers
Related