【问题标题】:How to get the original input using Joi.raw()如何使用 Joi.raw() 获取原始输入
【发布时间】:2018-09-02 19:37:23
【问题描述】:

我正在尝试使用hapijs/joijoi-date-extensions 验证一些输入。我写了这段代码example1.js:

const BaseJoi = require('joi');
const Extension = require('joi-date-extensions');
const Joi = BaseJoi.extend(Extension);



const schema = Joi.object().keys({
start_date: Joi.date().format('YYYY-MM-DD').raw(),
end_date: Joi.date().min(Joi.ref('start_date')).format('YYYY-MM-DD').raw(),
});

const obj =  {
start_date: '2018-07-01',
end_date: '2018-06-30',
}

console.log(schema.validate(obj));

代码返回此错误:

child "end_date" fails because ["end_date" must be larger than or equal to "Sun Jul 01 2018 01:00:00 GMT+0100 (CET)"]

但是我想在错误中获取原始输入,类似这样:

child "end_date" fails because ["end_date" must be larger than or equal to "2018-07-01"]

当我在 example2.js 中尝试这条指令时:

start_date =  Joi.date().format('YYYY-MM-DD');
console.log(start_date.validate('2018-07-31'));

结果是:

Tue Jul 31 2018 00:00:00 GMT+0100 (CET)

当我在 example3.js 中使用raw() 时:

start_date =  Joi.date().format('YYYY-MM-DD').raw();
console.log(start_date.validate('2018-07-31'));

它返回:

"2018-07-31"

在 example1.js 中,我想获取我的代码输入的原始日期。我该如何解决?

【问题讨论】:

    标签: node.js validation hapijs joi


    【解决方案1】:

    .raw 控制数据如何传输到Joi.validate 的回调,即验证过程​​后数据的样子。它确实控制错误发生的情况。

    为此,您可能需要使用.error。我从未使用过它,但我想它会是这样的:

    Joi.date().min(Joi.ref('start_date')).format('YYYY-MM-DD').raw().error(function (errors) {
      var out = [];
      errors.forEach(function (e) {
        out.push(e.message.replace(/".*?"/g, function(match) {
          var dateMatch = Date.parse(match);
          if (isNaN(dateMatch)) {
            return match;
          } else {
            // return formatted date from `dateMatch` here, too lazy to write it in p[l]ain JS...
          }
        }));
      });
      return out;
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      相关资源
      最近更新 更多