Skip to content

Option to validate a date format but not convert to a date object #509

@sandfox

Description

@sandfox

Is there a way to apply a Joi.date().format() to a string so that it will validate it but not transform the value into a date object?

The context of this is that I have a hapijs app with a controller that looks roughly like this.

var controllerPostConfig = {
    validate: {
        payload: Joi.object().keys({
            day: Joi.date().format('YYYY-MM-DD').required(),
            start_time: Joi.date().format('HH:mm:ssZ').required(),
            end_time: Joi.date().format('HH:mm:ssZ').required(),
            user_id: Joi.string().required()
        }).without('day', ['before', 'after'])
        .or(['user_id', 'before', 'after', 'day'])
    },
    handler: function(request, reply) {

        windowDao.create(this.db, request.payload, function(err, window){
            return reply(responseFormatter.resource(window));
        })
    }
}

I'd like to check that day, start_time, end_time are in valid date formats. but I'd like the output of the validation to still be strings (as long as they are valid) because thats the format my database is expecting them in, and adding another transformation layer/function somewhere else in the app seems error prone.

The only work around I can think of is to attempt to regex the incoming strings but that feels semantically wrong and also prone to errors.

Let me know if this isn't clear, or you think is too much of edge case, or just better handled outside of Joi

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions