[英]Date validation using joi - invalid date isn't throwing an error 2019-11-31
I am trying to use JOI to check that a date is a valid date and also not in the future.我正在尝试使用 JOI 来检查日期是否是有效日期,也不是将来的日期。 I would expect 31 November 2001 to fail because there is no 31 November.. however it it passes!我预计 2001 年 11 月 31 日会失败,因为没有 11 月 31 日……不管它过去了!
Strangely 32 November 2001 fails?奇怪的是 2001 年 11 月 32 日失败了? Any idea what the problem is?知道问题是什么吗? My test code is below我的测试代码如下
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)
adding another .format
did the trick添加另一个.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',
}
})
For anyone coming later, I manage to validate the 31ths as follows:对于后来的任何人,我设法按如下方式验证 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')
})
The otherwise regex is just for allowing a custom message, otherwise it would only say that none of the alternatives were fulfilled. otherwise 正则表达式仅用于允许自定义消息,否则它只会说没有任何备选方案得到满足。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.