2016-03-03 34 views
0

定義我的路由時,我希望能夠驗證傳入參數是否爲數組,如果不是,則會引發錯誤。到目前爲止,我一直在使用express-form進行所有驗證,並且似乎無法找到驗證陣列的方法。我知道我可以使用express-validate這樣做,但我想繼續使用迄今爲止使用的內容,以便所有內容看起來均勻。如何驗證表單中的數組

app.post(
    '/addUserInfo', 
    form(
     field('userID').trim().required().is(idRegex) 
     // Need similar check for 'items' field here 
    ), 
    offline.addUserInfo 
); 

回答

1

它在docs

您可以使用:

更新 正如在評論中提及的值是字符串,需要被解析到陣列

field('items').custom(function(value){ 

    // check if value is array, throw error if not 

    //if(value instanceof Array) return; 

    if(JSON.parse(value) instanceof Array) return; 

    throw new Error('The field "items" is not an array'); 

}); 
+0

哎呀,我想我錯過了。我通過將'if'更改爲'JSON.parse(value)instanceof Array'來得到這個結果。謝謝 :) – Ali