Express Validator - 如何打破验证链?

Express Validatior - How Do I Break The Validation Chain?

我有一个日期字段,我想确保其格式有效,如果是,则用户已年满 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

中找不到任何内容

你可以使用 momentjs strict mode together with String + Format parsing using moment.ISO_8601 (or 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!');
    }
  }),