Search code examples
javascriptnode.jstypescriptjoi

Validate date using Joi without convert it to utc format


Is there is a way to validate a date using @joi/date but without changing the date to UTC format.

I'm trying to validate the date before I send it to the DB

What I tried

const Joi = require('joi').extend(require('@joi/date'));
...
    const schema = Joi.object({
        f_title: Joi.string().required(),
        date: Joi.date().format('YYYY-MM-DD').required(),
    });

But the problem is that 2000-05-15 will always be converted to 2000-05-15T21:00:00.000Z and the DB will raise an incorrect date value.

Thanks : )


Solution

  • A possible workaround is to initiate a new date object from the date the user has sent, and next, you can get the full year, month, and day... also if you use this way, you will get the date in this format no matter what browser the user is using.

    const Joi = require('joi').extend(require('@joi/date'));
    ...
        const schema = Joi.object({
            f_title: Joi.string().required(),
            dateVarFromUser: Joi.date().format('YYYY-MM-DD').required(),
        });
    ###
    // Rest of your code
    ###
    
    Before sending the request to the DB, add the following
    
    const datObj = new Date(dateVarFromUser);
    dateVarFromUser = datObj.getFullYear() + '-' + (datObj.getMonth()+1) + '-' + datObj.getDate()
    
    ###
    // Then, you could send it to the SQL handler/function
    ###