Joi 验证中从开始到结束的限制范围

问题描述 投票:0回答:1

在nodeJs中添加Joi验证,以限制endDate不超过startDate之后3年。

示例: 开始日期 2024-03-29 , 最大结束日期应为:2027-03-29。

我尝试过:

const maxEndDate = Joi.ref('startDate', {
  adjust: startDate => startDate.getTime() + 1000 * 60 * 60 * 24 * (365 * 3)
});

const validate =
  query: {
    endDate: Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).raw().required(),
  }

const maxEndDate = Joi.ref('startDate', { adjust: ['+3 years'] })

但看起来它没有添加 3 年,它只以 startDate 作为参考并给出错误:

"message": "\"endDate\" must be less than or equal to \"Fri Mar 29 2024 03:00:00 GMT+0300\"
javascript node.js validation backend joi
1个回答
0
投票

需要进行一些更正。

  1. 定义 maxEndDate 时,需要使用
    .iso()
    方法 确保 Joi 将其解析为 ISO 日期。
  2. 定义验证模式时,您应该使用
    Joi.object()
    来包装查询对象。

你可以尝试:

const maxEndDate = Joi.ref('startDate', {
  adjust: startDate => startDate.getTime() + (1000 * 60 * 60 * 24 * 365 * 3) 
}).iso();

而不是:

const maxEndDate = Joi.ref('startDate', {
  adjust: startDate => startDate.getTime() + 1000 * 60 * 60 * 24 * (365 * 3)
});

还有

const validate = Joi.object({
  query: Joi.object({
    startDate: Joi.date().format(DATE_FORMAT).utc().required(),
    endDate: Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).required(),
  })
});

代替:

const validate =
      query: {
        endDate: 
Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).raw().required(),
      }
© www.soinside.com 2019 - 2024. All rights reserved.