转自https://www.cnblogs.com/xiawuyi/
业务场景是mac地址既要验证唯一性又要验证格式是否正确,但源码中controller中仅仅是返回true或者false,无法满足业务需求,必须修改validate.js源码。
controller中代码改为:
@ResponseBody @RequiresPermissions("sys:user:edit") @RequestMapping(value = "checkMac") public String checkMac(String oldMacAddress, String macAddress,HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); if (macAddress != null &&(macAddress.equals(oldMacAddress)||systemService.getUserByMacAddress(macAddress) == null)) { String reg_mac= "^[A-F0-9]{2}(-[A-F0-9]{2}){5}$"; if((!Pattern.compile(reg_mac).matcher(macAddress).find())){ map.put("success", false); map.put("message", "MAC地址格式不正确"); }else{ map.put("success", true); } } else { map.put("success", false); map.put("message", "MAC地址已存在"); } return renderString(response,map); }
注意返回数据格变量和js中要获取的变量必须一致,而且必须为json格式
validate.js:修改remote中的success方法,success: function(response) 这里的 response是remote请求checkMac方法返回的json数据,
现在checkMac方法返回类型已经修改,所以该回调函数中的代码也要做相应的修改:
success回调函数中,将这两行代码:
validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response === true; 修改为 var tempResponse = response; if (tempResponse.success != undefined) { response = tempResponse.success; } if (tempResponse.message != undefined) { validator.settings.messages[element.name].remote = tempResponse.message; } else { validator.settings.messages[element.name].remote = previous.originalMessage; } var valid = response === true;
好了,问题解决了