validate 動態返回錯誤資訊
阿新 • • 發佈:2020-12-24
引入相關js
<!-- jquery-validate 表單驗證外掛 --> <script th:src="@{/theme/ajax/libs/validate/jquery.validate.js}"></script> <script th:src="@{/theme/ajax/libs/validate/validate-methods.js}"></script> <script th:src="@{/theme/ajax/libs/validate/messages_zh.min.js}"></script> <script th:src="@{/theme/ajax/libs/validate/old/jquery.validate.extend.js}"></script>
示例
<div class="form-group"> <label class="col-sm-3 control-label">部門名稱:</label> <div class="col-sm-8"> <input class="form-control" type="text" name="deptName" id="deptName" required> </div> </div> $("#form-dept-add").validate({ onkeyup: false, rules:{ deptName:{ required: true, checkDeptUnique :true //自定義addMethod方法 /* 不用這種方式,不能自定義返回資訊 remote: { url: ctx + "system/SysDeptController/checkDeptUnique", type: "post", dataType: "json", data: { "parentId": function() { return $("input[name='parentId']").val(); }, "deptName" : function() { return $.common.trim($("#deptName").val()); } }, dataFilter: function(data, type) { data = JSON.parse(data); msgs = data.msg; return {success:true,messages:"222"}; //return $.validate.unique(data.code); } } */ }, orderNum:{ digits:true }, email:{ email:true, }, phone:{ isPhone:true, }, }, messages: { deptName: { required: "已存在" } /* "deptName": { remote: msgs } */ }, focusCleanup: true });
addMethod新增
validate-methods.js ... //校驗部門唯一 jQuery.validator.addMethod("checkDeptUnique", function (value, element, param) { var flag = true ; var result = '' ; $.ajax({ url: ctx + "system/SysDeptController/checkDeptUnique", data : { deptName : value, "parentId": function() { return $("input[name='parentId']").val(); }, }, async : false, type: "post", dataType: "json", success : function(data) { if(data.code == "0" || data.code == 0 ) { flag = true; }else{ flag = false ; result = data.msg ; } } }); $.validator.messages.checkDeptUnique = result; return flag; }) ;
相關java返回值示例, AjaxResult為自定義的返回類
/**
* 校驗部門名稱 或 部門code
*/
@PostMapping(value="/checkDeptUnique",produces="application/json;charset=UTF-8")
@ResponseBody
public AjaxResult checkDeptNameUnique(SysDept dept) {
if (StringUtils.isNull(dept.getDeptName()) ||
StringUtils.isEmpty(dept.getDeptName())) {
return AjaxResult.warn("缺少引數deptName", dept);
}
dept = iSysDeptService.checkDeptNameUnique(dept);
if (dept != null) {
return new AjaxResult(Type.ERROR, "存在重複資料", dept);
}
return AjaxResult.success();
}
//返回示例物件
{"msg":"存在重複資料","code":500,"data":{"deptName":"123","deptCode":null}}