做表單驗證的最佳做法是什麼?特別是當我只有兩個字段被傳遞到後端時。在窗體中驗證字段是一個在MVC中的INT
1)產品ID(我需要確保他們指的是他們能夠獲得的產品。) 2)按鍵數(它必須是一個INT數據類型)
我有提交一個表單產品ID(從下拉菜單中)和該產品的密鑰數量。我看着我的代碼看起來很醜,看起來並不是一個好習慣。當我打電話給服務時,它只接受一個INT。
我現在的代碼如下。
if(StringUtils.isEmpty(downloadFormBean.getNbrEcus())){
logger.debug("User did not enter the number of Keys");
model.addAttribute("ERROR","Please enter the number of ECU IDs.");
}else if(!m.containsKey(downloadFormBean.getProduct()) && !m.containsValue(downloadFormBean.getProduct())){
logger.debug("User attempted to pass a product that was not returned to him. Product:" +downloadFormBean.getProduct());
model.addAttribute("ERROR","You must submit a product you were provided.");
}else if(!NumberUtils.isDigits(downloadFormBean.getNbrEcus())){
logger.debug("User attempted to pass an invalid integer");
model.addAttribute("ERROR","Please enter a valid integer number!");
}else if(Long.parseLong(downloadFormBean.getNbrEcus()) > 2147483647){
logger.debug("User attempted to pass a number larger than 2137483647.");
model.addAttribute("ERROR","You are attempting to request too many Keys.");
}else if(Integer.parseInt(downloadFormBean.getNbrEcus()) == 0){
logger.debug("User attempted to submit zero requests.");
model.addAttribute("ERROR","You must request at least one Key");
正在做這樣的事情http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-example/甚至值得麻煩,它會檢查INT。
任何批評是高度重視
對於整數,只需嘗試將字符串解析爲一個int。如果拋出異常,則知道該字符串不是int。如果產品ID不只是一個整數,您可以考慮使用正則表達式。編寫一個正則表達式,它將匹配有效的產品ID,但不包含其他任何內容。 –