項目中經(jīng)常會遇到需要后臺驗證問題,如用戶名、用戶賬號是否存在等。使用jQuery Validate插件可以使用remote校驗規(guī)則完成驗證。
示例:
一.基本用法
1.需要驗證的表單
<form id="registForm"> <input type="text" id="username" name="username"> </form>
2.js
使用remote校驗規(guī)則,最簡單粗暴的寫法是remote: url,此時請求的url后面自動拼接當(dāng)前驗證的值,例如下面的寫法,請求的url為:xxx/checkUsername.do?username=test
// 導(dǎo)入jquery、validte庫略$(function() { $.validator.setDefaults({ submitHandler: function(form) { // 驗證通過處理 ... } }); $("#registForm").validate({ rules: { username: { required: true, remote: "checkUsername.do" }, }, messages: { username: { required: "用戶名不能為空", remote: "用戶名已經(jīng)存在" } } });});
3.后臺(Spring MVC測試)
后臺響應(yīng)只能輸出true或false,不能有其他數(shù)據(jù),true:驗證通過,false:驗證失敗;設(shè)置返回類型為boolean或String都可以
(1).返回boolean
@RequestMapping("/checkUsername")public @ResponseBody boolean checkUsername(@RequestParam String username) { // 測試 return !"test".equals(username);}
(2).返回String
@RequestMapping("/checkUsername")public @ResponseBody String checkUsername(@RequestParam String username) { // 測試 return !"test".equals(username) ? "true" : "false";}
二.其他用法
上面的用法不能滿足實際的需求,有時候會有需要提交其他參數(shù)、參數(shù)名和屬性名不一致或請求方式為POST的情況,寫法如下:
1.js
使用data選項,也就是jQuery的$.ajax({...})的寫法;
提交的數(shù)據(jù)需要通過函數(shù)返回值的方式,直接寫值有問題;
默認(rèn)會提交當(dāng)前驗證的值,也就是下例中的 username: xxx會被默認(rèn)作為參數(shù)提交
....username: { required: true, remote: { url: "checkUsername.do", type: "post", //數(shù)據(jù)發(fā)送方式 dataType: "json", //接受數(shù)據(jù)格式 data: { //要傳遞的數(shù)據(jù) username: function() { return $("#username").val(); }, extra: function() { return "額外信息"; } } }}
2.后臺
限制了必須為POST方式請求
@RequestMapping(value = "/checkUsername", method = RequestMethod.POST)public @ResponseBody boolean checkUsername(User user, @RequestParam String extra) { // 測試 System.out.println(extra); return !"test".equals(user.getUsername());}
參考文章:http://www.runoob.com/jquery/jquery-plugin-validate.html
以上這篇jQuery Validate插件ajax方式驗證輸入值的實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答