【问题标题】:JOI validation to validare object from a given array of objectsJOI 验证以验证给定对象数组中的对象
【发布时间】:2025-12-01 15:40:01
【问题描述】:

我的请求正文包含一个 Javascript/JSON 对象:

{ id: 1, value: "example 1"}

我有一个允许的对象列表:

[
  { id: 1, value: "example 1" } ,
  { id: 2, value: "example 2" } ,
  { id: 3, value: "example 3" } ,
]

我正在写一个Joi schema 并想验证请求正文中的对象是否在我的允许值列表中。

【问题讨论】:

    标签: joi


    【解决方案1】:

    您需要使用 Joi 的 any.custom() 属性:https://joi.dev/api/?v=17.2.1#anycustommethod-description。你需要一个类似于

    的函数
    const _ = require('lodash');
    
    const allowed = [
      { id: 1, value: 'value 1' } ,
      ...
      { id: 9, value: 'value 9' },
    ];
    
    function isOneOf(allowedValues) {
      return (v, helpers) => {
        if ( ! _.some(allowedValues, x => _.isEqual(x,v) ) {
          return helpers.error('naughty!');
        }
      };
    }
    

    您应该可以按照以下方式使用:

    ...any().custom( isOneOf(allowedValues) );
    

    【讨论】:

      【解决方案2】:

      我假设数组中的 id 是唯一的

      yourObj = {id:1,value: "example 1"};
      
      yourArray = [{id:1,value: "example 1"},{id:2,value: "example 2"},{id:3,value: "example 3"}]
      
      isObjectAvailable = yourArray.some(el=>el.id===yourObj.id)
      console.log(isObjectAvailable) // return true if found else false
      

      【讨论】:

      • 所以你的意思是我需要添加自定义验证?
      【解决方案3】:

      假设您希望您的架构验证此对象数组。

      const example = {
            "id": 1,
            "value": "example1"
         };
      

      Joi 架构应该是

      var validator = require('@hapi/joi');
      
      const rules = validator.object().keys({
              id: validator.number().required(),
              value: validator.string().required()
          })
      
      

      【讨论】:

      • 不,对象必须存在于给定数组中才能通过验证