javascript 使用joi验证日期-无效日期不会抛出错误2019-11-31

xe55xuns  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(107)

我正在尝试使用JOI来检查日期是否是有效日期,也不是将来的日期。我希望2001年11月31日失败,因为没有11月31日...但是它通过了!
奇怪的是2001年11月32日失败了!知道是什么问题吗?我的测试代码如下

const joi = require('joi')
const moment = require('moment')

const schema = joi.object({
    location: joi.string().strict().trim().min(1).required().error(() => {
        return {
            message: 'A location must be entered',
        }
    }),
    incidentDate: joi.date().max(moment().format('YYYY-MM-DD')).required().error(() => {
        return {
            message: 'A date must be entered that is not in the future',
        }
    }),

})

const requestForm = {"dateOfIncident":{"day":"31","month":"11","year":"2001"},"location":"sdcds"}
const strDate   = `${requestForm.dateOfIncident.year}-${requestForm.dateOfIncident.month}-${requestForm.dateOfIncident.day}`

requestForm.incidentDate = strDate

const joiErrors = joi.validate(requestForm, schema, { stripUnknown: true })

console.log(joiErrors)
bprjcwpo

bprjcwpo1#

添加另一个.format就可以了

incidentDate: joi.date().format('YYYY-MM-DD').max(moment().format('YYYY-MM-DD')).required().error(() => {
        return {
            message: 'A date must be entered in the correct format that is not in the future',
        }
    })
6l7fqoea

6l7fqoea2#

对于稍后到来的任何人,我设法验证第31条如下:

const myDate = Joi.alternatives().conditional('myDate', {
    is: Joi.date().iso(),
    then: Joi.string().regex(/^((?!(([0-9]{4}-02-30|[0-9]{4}-02-31|[0-9]{4}-04-31|[0-9]{4}-06-31|[0-9]{4}-09-31|[0-9]{4}-11-31)(T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)?)).)*$/)
    .message('Date does not exist.'),
    otherwise: Joi.string().regex(/^(?!.)/).message('Date is not in a valid format')
})

否则regex只允许自定义消息,否则它只会说没有一个替代项被满足。

相关问题