【问题标题】:Joi schema.validate a custom type return an undefined valueJoi schema.validate 自定义类型返回未定义的值
【发布时间】:2020-04-03 02:16:12
【问题描述】:

我正在尝试使用 JOI 验证自定义类型,并进行转换。 我的 JoiType 的基本类型是 Joi.array()

当我尝试时

const schema = Joi.object().keys({
 attribute: Joi.array().items(Joi.string())
});

const result = schema.validate(exampleOfArray);

我发现result.value 包含真正的验证值。

但是当我将类型更改为自定义类型时,没有返回值 : (result.value === undefined)

这是我的自定义类型:

const customJoi = Joi.extend((joi: Root) => {
  return {
    type: 'stringArray',
    base: joi.array().items(joi.string()).meta({ baseType: 'array' }),
    coerce(value: any, helpers: CustomHelpers) {
      if (typeof value !== 'string') {
        return value;
      }
      if (!value) {
        return [];
      }
      return value.replace(/^,+|,+$/mg, '').split(',');
    }
  };
});

const schema = Joi.object().keys({
 attribute: customJoi.stringArray().items(Joi.string())
});

【问题讨论】:

    标签: javascript node.js hapijs joi hapi


    【解决方案1】:

    我找到了解决办法:

    强制函数应该返回:

    return { value: value };
    

    而不是:

    return value;
    

    【讨论】:

    • 这个答案拯救了我的一天!欢呼
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 2021-09-22
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多