代码之家  ›  专栏  ›  技术社区  ›  Slim

如何使用joi.raw()获取原始输入

  •  1
  • Slim  · 技术社区  · 6 年前

    我正在尝试用验证一些输入 hapijs/joi joi-date-extensions . 我编写了以下代码示例1.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)
    

    当我使用 raw() 在示例3.js中:

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

    它返回:

    "2018-07-31"
    

    在example1.js中,我希望得到由代码输入的原始日期。我怎样才能解决这个问题?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Stock Overflaw    6 年前

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