繁体   English   中英

使用 joi 进行日期验证 - 无效日期不会引发错误 2019-11-31

[英]Date validation using joi - invalid date isn't throwing an error 2019-11-31

我正在尝试使用 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)

添加另一个.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',
        }
    })

对于后来的任何人,我设法按如下方式验证 31ths:

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')
})

otherwise 正则表达式仅用于允许自定义消息,否则它只会说没有任何备选方案得到满足。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM