node.js - 如何使用 Joi.raw() 获取原始输入

标签 node.js validation hapi.js joi

我正在尝试使用 hapijs/joi 验证一些输入和 joi-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 中,我想获取代码输入的原始日期。我该如何解决这个问题?

最佳答案

.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;
})

关于node.js - 如何使用 Joi.raw() 获取原始输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51479741/

相关文章:

javascript - 从 webpack 中剥离动态需求

node.js - Nodejs抛出异常

javascript - 动态添加属性到sequelize.js查询

php - 函数/方法参数验证标准

validation - 来自通过 ActiveForm 分配的标签的 Yii2 模型验证消息

javascript - Codemirror 的 HTMLHint 验证器

node.js - 'ffmpeg' 在 Hapi js(Node js)中未被识别为内部或外部命令

javascript - AngularJS 中的 if/else 语句

node.js - 执行存储过程时出现node-oracledb错误NJS-012

node.js - 如何使用 Chai Http 发布对象数组