2017-07-14 42 views
0

我正在使用express-validator驗證我的請求數據。按照文檔添加他們,我們必須聲明它們這樣快速驗證程序:跳過自定義驗證程序中的進一步驗證

app.use(expressValidator({ 
customValidators: { 
    isArray: function(value) { 
     return Array.isArray(value); 
    }, 
    gte: function(param, num) { 
     return param >= num; 
    } 
} 
})); 

我添加了一個驗證它像文檔。但我只能返回true或false。

我想確保基於條件驗證器跳過進一步的鏈驗證。

回答

0

你可以分階段完成。在這裏,我首先檢查是否設置了用戶名,並且只有在通過後我才能進行昂貴的異步驗證。

req.checkBody('username') 
     .notEmpty().withMessage('Username is required.'); 

req.getValidationResult().then(result => { 
     if (!result.isEmpty()) { 
      return res.status(400).send(result.mapped()); 
     } 

     req.checkBody('username') 
      .isUserNameAvailable().withMessage('Username is not available.'); 

     req.getValidationResult().then(result => { 
      if (!result.isEmpty()) { 
       return res.status(400).send(result.mapped()); 
      } 
      next(); 
     }); 

}) 
+0

好吧,如果我有三個到四個驗證一個字段或不同的領域,你不覺得代碼會搞砸。應該有另一種方式來解決這個問題。 –