簡體   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