首先来说用户名验证:
前台:
<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:"请输入姓名" } } })