標籤:
jQuery Validate 外掛程式為表單提供了強大的驗證功能,讓用戶端表單驗證變得更簡單,同時提供了大量的定製選項,滿足應用程式各種需求。該外掛程式捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫使用者自訂方法的 API。
對於它基礎的驗證規則這裡不做贅述,主要講解它的非同步驗證。
需求如下:在一個form表中,需要根據使用者ID來驗證使用者名稱,若資料庫中已存在同樣的使用者ID對應同樣的記錄名稱,則禁止插入或更新(更新時若記錄名未發生改變,則需要再判斷是否除此記錄之外還存在同名稱的記錄)。
部分jsp頁面代碼如下:
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代碼如下:
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;
name的驗證由於要擷取到最新的值,因此只能採用這種比較笨重的方法,設定url,跳轉方式為post,資料類型為json,需要傳遞的資料放在data 中,包括:userId,oldName,name。
後台接收處理的方法代碼如下:
@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 傳過來的參數保持一致。
jquery validate 驗證基礎