javaBean中,validate校驗
阿新 • • 發佈:2018-11-02
1、bean中寫法:
/** 標題 */ @Length(max = 30, message = "只允許輸入30個字") @NotBlank(message = "請輸入標題") private String name; /** 獎勵額度 */ @Digits(integer = 8, fraction = 2) @NotBlank(message = "請輸入獎勵額度") private String price_setting; /** 達幣數量 */ @Digits(integer = 8, fraction = 2) @NotNull() private BigDecimal money;
2、controller中,根據情況判斷,顯示不同校驗資訊:
/** * 修改 * @param B008003Bean 畫面Bean * @param request * @return 返回上級頁面 */ @RequestMapping("/update.do") public String update(@ModelAttribute("b008003Bean") @Validated B008003Bean b008003Bean,BindingResult errors,HttpServletRequest request,Model model){ String strprice_setting = b008003Bean.getPrice_setting(); String strupperprice = b008003Bean.getUpperprice(); BigDecimal price_setting = new BigDecimal(strprice_setting); // 分情況顯示校驗資訊 if(price_setting.compareTo(new BigDecimal("0.01")) == -1){ errors.rejectValue("price_setting","","獎勵額度不可小於0.01。"); } if(!strprice_setting.equals("") && !strupperprice.equals("")){ BigDecimal upperprice = new BigDecimal(strupperprice); if(price_setting.compareTo(upperprice) == 1){ errors.rejectValue("price_setting","","獎勵額度不允許超出限額。"); } } if(errors.hasErrors()){ // 資料重新複製回頁面中 List<B008002TypeBean> categoryList = b008002Service.getCategorys(); b008003Bean.setCategoryList(categoryList); model.addAttribute("b008003Bean", b008003Bean); return "/b008/b008003"; } b008003Service.update(b008003Bean); // 返回上級頁面 return "redirect:/b008/b008001/init.do"; }
3、jsp中程式碼:
<div class="form-group"> <label class="col-sm-2 control-label"><i style = "color:red;padding-right: 5px;">*</i>完成獎勵:</label> <div class="col-sm-8"> <sf:input type="text" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" path="price_setting" placeholder="完成獎勵" class="form-control" required="" value="${b008003Bean.price_setting}"/> <sf:errors path="price_setting" cssStyle="color:red"/> </div> </div>