2016-05-12 62 views
0

定義有效鍵我有一個淳佳模式是這樣的:淳佳模式驗證:Joi.object從陣列

var schema = Joi.object().keys({ filter: Joi.object({ }) }) 

然後我對濾波器對象的所有有效鍵在名爲validKeys單獨的數組。

我想引用filter-object的validKeys。否則,我將不得不硬編碼這樣的允許值:

var schema = Joi.object().keys({ filter: Joi.object({ allowed1:Joi.string(), allowed2: Joi.string(), ... }) }) 

我不想這樣做。這是可能與Joi或其他Javascript工具?

回答

0

我不確定你的validkeys數組是什麼樣的,但是如果你先設置你的過濾模式,然後再設置你的最終模式,你可以遍歷你的鍵並動態地將它們添加到你的過濾模式中(假設它們'都應該是字符串)。

const joi = require('joi'); 

// not sure what valid key structure is like.. 
const validkeys = ['allowed1', 'allowed2', 'allowed3']; 

// set up filter schema first. 
let filterschema = {}; 

for (let i = 0; i < validkeys.length; i++) { 
    filterschema[validkeys[i]] = joi.string(); 
} 

// set up the final schema 
let finalschema = joi.object().keys({ 
    filter: filterschema 
}); 

// test 
let testobj = { 
    filter: { 
     allowed1: 'cuthbert', 
     allowed2: 'susan', 
     allowed5: 'jake' // should NOT be allowed. 
    } 
}; 

let result = joi.validate(testobj, finalschema); 

// should fail because key allowed5 isn't defined in filter schema. 
console.log(JSON.stringify(result, null, 2));