首先來說用戶名驗證:
前台:
<tr> <td class="tableleft">教師編號</td> <td><input type="text" name="tno" id="tno" required="required"/><div class="status" style="color:red"></div></td> </tr>
js部分:
var flag = true; $("#tno").blur(function(){ var tno = $("#tno").val(); $.ajax({ url:"admin/checktno.action", data:{tno:tno}, type:"post", datatype:"text", success:function(data){ if(data=="yes"){ $(".status").html(""); flag=true; }else{ $(".status").html("教工號已存在!"); flag=false; } }, errot:function(){ alert("error!"); } }); }); $("#submitbutton").click(function(){ if(flag){ $("#form").submit(); }else{ alert("請先滿足條件!"); } });
后台:
@RequestMapping("admin/checktno")
@ResponseBody
public String checkTno(Long tno) {
Teacher tea = teacherService.getTea(tno);
if(tea == null) {
return "yes";
}
return "no";
}
接下來簡單用jquery的jquery.validate插件
下載該插件,地址:https://jqueryvalidation.org/
導入:
<script type="text/javascript" src="Js/jquery.validate.min.js"></script>
接下來就是驗證部分的js:
$("#form").validate({
onsubmit:true,// 是否在提交時驗證
rules: {
tno: {
required: true,
minlength: 1
},
password: {
required: true,
minlength: 3
} ,
tname:{
required: true
}
},
messages: {
tno: {
required: "請輸入教工號",
minlength: "教工號至少為1位"
},
password: {
required: "請輸入密碼",
minlength: "密碼長度最少為3位"
},
tname:{
required:"請輸入姓名"
}
}
})
