validate外掛校驗表單--自定義校驗,Ajax非同步校驗使用者名稱是否存在
1.所需要的外掛下載地址(放到js目錄下)
https://pan.baidu.com/s/16KyrX16dzgGTIncho2WHmg
2.引入庫
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
3.編寫校驗檔案
<script type="text/javascript">
//自定義校驗規則
$.validator.addMethod(
//自定義校驗規則的名稱
"checkUsername",
//自定義規則校驗的函式
function(value,elements,params){
var flag = false ;
$.ajax({
"async":false, //必須是同步才能校驗成功
"url":"${pageContext.request.contextPath}/user?method=checkUsername",
"data":{"username":value},
"type":"POST",
"dataType":"json",
"success":function(data){
flag = data.isExit;
}
});
//返回false代表該校驗器不通過
return !flag ;
}
)
$(function(){
$("#myform").validate({
rules:{
"username":{
"required":true,
"checkUsername":true
},
"password":{
"required":true,
"rangelength":[6,12]
},
"repassword":{
"required":true,
"rangelength":[6,12],
"equalTo":"#password"
},
"email":{
"required":true,
"email":true
},
"sex":{
"required":true
}
},
messages:{
"username":{
"required":"使用者名稱不能為空哦!",
"checkUsername":"使用者名稱已經存在"
},
"password":{
"required":"密碼不能為空哦!",
"rangelength":"密碼長度必須為6-12位哦!"
},
"repassword":{
"required":"密碼不能為空哦!",
"rangelength":"密碼長度必須為6-12位哦!",
"equalTo":"兩次密碼不一致"
},
"email":{
"required":"郵箱不能為空哦!",
"email":"郵箱格式不正確"
},
"sex":{
"required":"必須選擇性別"
}
}
});
});
</script>
4.checkUsername
web層
public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收資料
String username = request.getParameter("username");
UserService service = new UserService();
boolean isExit = service.checkUsername(username);
//將資料寫回Ajax
String json = "{\"isExit\":"+isExit+"}";
response.getWriter().write(json);
}
service層
//校驗註冊時使用者名稱是否已經存在
public boolean checkUsername(String username) {
Long isExit = 0l;
try {
isExit = dao.checkUsername(username);
} catch (SQLException e) {
e.printStackTrace();
}
return isExit>0?true:false;
}
dao層
//註冊時校驗使用者名稱是否已經存在
public Long checkUsername(String username) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select count(*) from user where username=?";
Long query = (Long) qr.query(sql, new ScalarHandler(), username);
return query;
}