jQuery Validate 插件爲表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定製選項,知足應用程序各類需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫用戶自定義方法的 API。html
對於它基礎的驗證規則這裏不作贅述,主要講解它的異步驗證。數據庫
需求以下:在一個form表中,須要根據用戶ID來驗證用戶名,若數據庫中已存在一樣的用戶ID對應一樣的記錄名稱,則禁止插入或更新(更新時若記錄名未發生改變,則須要再判斷是否除此記錄以外還存在同名稱的記錄)。json
部分jsp頁面代碼以下:app
1 <div class="control-group"> 2 <label class="control-label">userId:</label> 3 4 <div class="controls"> 5 <form:input path="userId" htmlEscape="false" maxlength="64" class="input-xlarge "/> 6 <span class="help-inline"><font color="red">*</font> </span> 7 </div> 8 </div> 9 <div class="control-group"> 10 <label class="control-label">名稱:</label> 11 12 <div class="controls"> 13 <input type="hidden" id="oldName" name="oldName" value="${doctorPatientRecord.name}"/> 14 <form:input path="name" htmlEscape="false" maxlength="100" class="input-xlarge "/> 15 <span class="help-inline"><font color="red">*</font> </span> 16 </div> 17 </div>
上面有兩個須要用到的標籤:userId和name,另外爲了更新時是否爲改變記錄名而添加了一個新的input標籤,存放的是原記錄名這些標籤中有大量的屬性設置,實際上是非必須的,必定要用到的有標籤的name屬性,由於jQuery 驗證的時候是根據name屬性名來查找對象的。異步
jQuery代碼以下:jsp
rules: { userId: {required: true, remote: "${ctx}/doctor/doctorpatientrecord/checkUser?"}, name: { required: true, remote: { url: "${ctx}/doctor/doctorpatientrecord/checkName", type: "post", dataType: "json", data: { oldName:'${doctorPatientRecord.name}', name: function () { return $("#name").val(); }, userId: function () { return $("#userId").val(); } } } } }, messages: { userId: {required: "用戶ID不能爲空", remote: "用戶ID不存在"}, name: {required: "記錄名不能爲空", remote: "記錄名已存在"} },
jQuery代碼中一共有兩個驗證,一個是驗證userId一個是驗證name,也就是咱們的需求驗證。其中userId的驗證看起來很簡便,因爲我的理解及瞭解很少,只知道相對於name的驗證方式,userId所使用的這種驗證方式沒法獲取到最新的標籤值。而在form中,userId的值是默認不會發生改變的,所以能夠採用這種方法,userId的值已經傳入到後臺而不須要特意在url後去添加一個userId=xxxx;post
name的驗證因爲要獲取到最新的值,所以只能採用這種比較笨重的方法,設置url,跳轉方式爲post,數據類型爲json,須要傳遞的數據放在data 中,包括:userId,oldName,name。ui
後臺接收處理的方法代碼以下:url
@RequestMapping(value = "checkUser") public String checkUser(String userId) { if (userId != null) { UserToken userToken = new UserToken(); userToken.setUserId(userId); userToken = doctorUserTokenDao.get(userToken); if (userToken != null) { return "true"; } } return "false"; } /** * 驗證記錄名是否有效 */ @ResponseBody @RequiresPermissions("doctor:doctorpatientrecord:edit") @RequestMapping(value = "checkName") public String checkName(String oldName, String name, String userId) { if (name != null && name.equals(oldName)) { return "true"; } else if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(userId)) { DoctorPatientRecord doctorPatientRecord = new DoctorPatientRecord(); doctorPatientRecord.setName(name); doctorPatientRecord.setUserId(userId); List<DoctorPatientRecord> doctorPatientRecordList = doctorPatientRecordService.findListy(doctorPatientRecord); if (doctorPatientRecordList.size() == 0) { return "true"; } } return "false"; }
jQuery validate 後臺驗證返回的結果只能是 true 字符串或者false字符串,不能是其餘的值。後臺接收的參數命名必須和jQuery 傳過來的參數保持一致。spa