我有一个日期字段,我想确保它是有效格式,如果是18岁以上的用户,则为有效格式。格式为YYYY-MM-DD
。
这是我的验证器之一-失败的验证器:
body('birthday', 'Date format should be: YYYY-MM-DD')
.isRFC3339()
.custom(date => {
const over18 = moment().diff(date, 'years') >= 18;
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),
当前发生的情况是,如果日期不是RFC3339日期,则验证链会继续。这是有问题的,因为如果我传递格式错误的日期,moment
会产生错误。
如何调用.isRFC3339()
之后断开链,以便如果日期无效,则自定义验证程序将不会运行?我在docs
答案 0 :(得分:1)
您可以将momentjs strict mode与String + Format一起使用moment.ISO_8601
(或moment.HTML5_FMT.DATE
)special formats进行解析。
您的代码可能如下:
body('birthday', 'Date format should be: YYYY-MM-DD')
// .isRFC3339() // no more needed
.custom(date => {
const mDate = moment(date, moment.ISO_8601, true);
const over18 = moment().diff(mDate, 'years') >= 18;
if(!mDate.isValid()) {
return Promise.reject('Date is not YYYY-MM-DD');
if(!over18) {
return Promise.reject('You must be 18 or over!');
}
}),