【问题标题】:how to validate joi sub-schema in best way如何以最佳方式验证 joi 子模式
【发布时间】:2019-04-26 19:36:54
【问题描述】:

是否可以验证joi 架构而不会出现转换错误?即我有 N 个字段,但我只想验证 1 个字段。

我尝试了2种方法,如下:

const Joi = require("joi");
const _ = require('lodash');
const testSchema = Joi.object().keys({
    name: Joi.string().trim().min(5).max(25).required(),
    allowed: Joi.number().integer().min(0).max(1).default(0)
});

// works smoothly; no error
// const {error, value} = Joi.validate({name :"abc", allowed: 1}, testSchema);

// (Way 1) --> Error: "value" must be a number
// const {error, value} = Joi.validate({name :"abc", allowed: 1}, Joi.reach(testSchema, 'allowed'));

// (Way 2) --> Error: "value" must be a number
const {error, value} = Joi.validate({name :"abc", allowed: 1}, _.find(testSchema._inner.children, {key: 'allowed'}).schema);

console.log(error);

附:我知道 第三种 方法可以从较小的模式组合最终模式,但我不想这样做。

【问题讨论】:

    标签: javascript node.js validation schema joi


    【解决方案1】:

    只传递键的值而不是键值对象,例如:

    Joi.validate(1, Joi.reach(testSchema, 'allowed'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 2021-04-16
      • 2019-08-03
      • 2021-10-25
      • 1970-01-01
      • 2015-04-26
      相关资源
      最近更新 更多