代码之家  ›  专栏  ›  技术社区  ›  Zeeshan Hassan Memon

如何以最佳方式验证joi子模式

  •  0
  • Zeeshan Hassan Memon  · 技术社区  · 6 年前

    是否可以验证 joi 架构没有得到转换错误?i、 我有 但我想验证 仅限字段。

    方法如下:

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

    另外,我知道 从较小的模式合成最终模式的方法,但我不想这样做。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Zeeshan Hassan Memon    6 年前

    不传递key-value对象,只传递键的值,如:

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