hapijs / joi-date

Joi extensions for dates
Other
83 stars 25 forks source link

Issue with ".format" and number restriction #14

Closed david-unergie closed 4 years ago

david-unergie commented 5 years ago

Context

What are you trying to achieve or the steps to reproduce ?

joi.date() accepts a valid date string or a number of milliseconds. Using .format() should accept a valid date string, and should reject number in this case.

Working with joi v9.2.0:

const joi = require('joi')
joi.date().format('YYYY-MM-DD').raw().validate(12)
// => error "value" must be a string with one of the following formats YYYY-MM-DD

Failing with v10.6.0 / v11.4.0 / v12.0.0 / v13.7.0 / v14.3.0:

const joi = require('joi').extend(require('joi-date-extensions'))
joi.date().format('YYYY-MM-DD').raw().validate(12)
// => no error, return Number(12)

Which result you had ?

A number

What did you expect ?

An error: "value" must be a string with one of the following formats [YYYY-MM-DD]

hueniverse commented 4 years ago

format() only applies to strings. I would argue the old behavior was incorrect.

david-unergie commented 4 years ago

In this case @hueniverse, how to implement a "joi.date()" in order to allow string only?

hueniverse commented 4 years ago

Use Joi.string() with a regex pattern. There is no option to not allow numbers as input.

david-unergie commented 4 years ago

But in this case, there is no validation about the date consistency. For example, "2019-13-48" will be accepted…

hueniverse commented 4 years ago

Like I said, this is not a supported use case. In v16 you can write a custom function validator that checks helpers.original to be a string.

david-unergie commented 4 years ago

Ok. I just wanted to point out that the old behaviour may not be so bad. Thanks.

shadrech commented 4 years ago

I concur with @david-unergie. Maybe add a new field which forces input to only be a string? Old behaviour is far more logical as it abides by the set format(...) check