【问题标题】:Date validation using joi - invalid date isn't throwing an error 2019-11-31使用 joi 验证日期 - 无效日期不会引发错误 2019-11-31
【发布时间】:2019-12-13 18:49:55
【问题描述】:

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

【问题讨论】:

    标签: javascript momentjs joi


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多