基于Jquery Validate 的表单验证

时间:2023-03-09 06:49:19
基于Jquery Validate 的表单验证

基于Jquery Validate 的表单验证

  jquery.validate.js是jquery下的一个验证插件,运用此插件我们可以很便捷的对表单元素进行格式验证。

  在讲述基于Jquery Validate的表单验证前,我们先回顾一下基础纯JS的表单验证。

1、回顾基于JS的表单验证

  我们先写一个简单的验证邮箱、手机号的表单,页面代码如下:

 <form action="XXXX.action"  method="post" onsubmit="return checkNull();">
  <p>
    <span class="pSpan">邮 箱:</span>
    <input type="text" id="userMail" maxLength="100" onclick="clearSpan2(this,'span7')" onchange="check(this,2,'span7')" />
    <span id="span7" style="color: red; font-size: 13px;"></span>
  </p>
  <p>
    <span class="pSpan">手机号:</span>
    <input type="text" id="userPhone" onchange="check(this,3,'span8')" onclick="clearSpan2(this,'span8')" />
    <span id="span8" style="color:red;font-size:13px;"></span>
  </p>
  <p>
    <input type="submit" value="确认" />
    <input type="reset" value="重置" onclick="clearSpan()" />
</p>
</form> 

 JS代码如下:

 1 function getObj(id){
2 return document.getElementById(id);
3 }
4
5 /* 检查输入信息是否为空*/
6 function checkNull(){
7 if(getObj("userMail").value!=""){
8 check(check(getObj("userMail"),2,"span7"));
9 }else{
10 getObj("span7").innerHTML="";
11 }
12 if(getObj("userPhone").value!=""){
13 check(check(getObj("userPhone"),3,"span8"));
14 }else{
15 getObj("span8").innerHTML="";
16 }
17 if(getObj("span7").innerHTML!=""||getObj("span8").innerHTML!=""){ //判断提示信息是否为空
18 return false;
19 }
20 return true;
21 }
22 /* 清楚验证提示信息 */
23 function clearSpan(){
24 getObj("span7").innerHTML="";
25 getObj("span8").innerHTML="";
26 }
27
28 /* 若未输入信息,则根据id清除提示信息*/
29 function clearSpan2(id,spanId){
30 if(id.value==""){
31 getObj(spanId).innerHTML="";
32 }
33 }
34
35 /* 显示格式错误提示信息 */
36 function check(str, flag, spanId) {
37 var span = getObj(spanId);
38 switch (flag) {
39 case 2:// 邮箱
40 if (str.value!=""&&checkByRegExp(str.value, 2) == false) {
41 span.innerHTML = "填写的邮箱格式不正确!";
42 str.value = "";
43 } else {
44 span.innerHTML = "";
45 }
46 break;
47
48 case 3:// 手机号
49 if (str.value!=""&&checkByRegExp(str.value, 3) == false) {
50 span.innerHTML = "填写的手机号码格式不正确!";
51 str.value = "";
52 } else {
53 span.innerHTML = "";
54 }
55 break;
56 }
57
58 }
 // 验证数据格式
function checkByRegExp(str, flag) {
  switch (flag) {
  case 2:
    var reg = new RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/);
    return reg.test(str);// 邮箱格式
    break;
  case 3:
    var reg = new RegExp(/^0?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/);
    return reg.test(str);// 手机号格式
    break;
  }
}

  采用传统的JS验证时,我们不仅要在数据输入格式错误时进行提示,在表单提交前还要再次进行格式验证。本例子,采用判断提示信息是否为空,来判定数据输入格式是否正确。这样的表单验证操作繁琐,效率低下。

2、对Jquery Validate 简单介绍

  (本介绍内容引用自:http://blog.csdn.net/zzq58157383/article/details/7718352,此文详细介绍了Jquery Validate 插件的使用。)

  最常使用JavaScript的场合就是表单的验证,而jQuery作为一个优秀的JavaScript库,也提供了一个优秀的表单验证插件----Validation。Validation是历史最悠久的jQuery插件之一,经过了全球范围内不同项目的验证,并得到了许多Web开发者的好评。作为一个标准的验证方法库,Validation拥有如下特点:

  1.内置验证规则: 拥有必填、数字、Email、URL和信用卡号码等19类内置验证规则

  2.自定义验证规则: 可以很方便地自定义验证规则

  3.简单强大的验证信息提示: 默认了验证信息提示,并提供自定义覆盖默认的提示信息的功能

  4.实时验证: 可能通过keyup或blur事件触发验证,而不仅仅在表单提交的时候验证

3、使用Jquery Validate 插件(简单的重置密码功能)

  1、引用引入jQuery库和Validate插件

 <script type="text/javascript" src="../jquery-ui-1.9.0/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../jquery-validation-1.10.0/dist/jquery.validate.js"></script>

  下载链接:http://jquery.com/

  2、使用实例

  本示例验证项为原密码、新密码、确认密码,其中原密码的验证需要发送至后台进行验证(AJAX),并根据返回值判断其输入是否正确。新密码、再次输入密码数据的验证就直接使用validate插件提供的功能即可完成,而原密码的验证需要我们使用 jQuery.validator.addMethod方法建立一个新的验证方式。

 <body>
<form action="XXXX.action" method="post" id="form1">
<table width="100%" cellpadding="0" cellspacing="0" style="border-collapse: collapse;font-size: 12px;">
<tr height="40px">
<td width="15%" align="right">原密码:</td>
<td>
<input type="password" id="oldPassword" name="oldPassword" style="width: 60%;height:30px;line-height:30px; " />
</td>
</tr>
<tr height="40px">
<td width="15%" align="right">新密码:</td>
<td>
<input type="password" id="newPassword" name="newPassword" style="width: 60%;height:30px;line-height:30px;" />
</td>
</tr>
<tr height="40px">
<td width="15%" align="right">确认密码:</td>
<td>
<input type="password" id="rePassword" name="rePassword" style="width: 60%;height:30px;line-height:30px;" />
</td>
</tr>
<tr height="40px">
<td colspan="2"></td>
</tr>
<tr height="40px">
<td></td>
<td>
<div style="width:15%;float:left;">&nbsp;</div>
<div id="save1" style="width: 71px;height: 23px;text-align: center;line-height: 23px;font-size: 14px;color: white;float: left;">保存</div>
         <div style="width:50px;float:left;">&nbsp;</div>
<div id="reset1" style="width: 71px;height: 23px;;text-align: center;line-height: 23px;font-size: 14px;color: white;float: left;">重置 </div>
</td>
</tr>
</table>
</form>
</body>
<script type="text/javascript">
$("#reset1").click(function(){
$("#form1")[0].reset();
}); jQuery.validator.addMethod("isPwd", function(value, element) {
var result = false;
$.ajax({
url : "XXXX.action?v=" + Math.random(),
type : "post", //数据发送方式
dataType : "text", //接受数据格式
async : false,
data : {
oldPassword : $("#oldPassword").val()
},
success : function(data, textStatus) {
result = data == "T";
}
});
return this.optional(element) || (result);
}, ""); $(function() {
$("#form1").validate({
rules : {
"oldPassword" : {
required : true,
isPwd:true
},
"newPassword" : {
required : true,
minlength : 3
},
"rePassword" : {
required : true,
minlength : 3,
equalTo : "#newPassword"
}
},
messages : {
"oldPassword" : {
required : "<span style='color:red;'>请输入当前使用密码</span>",
isPwd : "<span style='color:red;'>请输入正确的密码</span>"
},
"newPassword" : {
required : "<span style='color:red;'>请输入您的新密码</span>",
minlength : "<span style='color:red;'>确认密码不能小于3个字符</span>"
},
"rePassword" : {
required : "<span style='color:red;'>请输入确认密码",
minlength : "<span style='color:red;'>确认密码不能小于3个字符</span>",
equalTo : "<span style='color:red;'>两次输入密码不一致</span>"
}
},
/* 设置验证触发事件 */
focusInvalid : false,
onkeyup : false, /* 设置错误信息提示DOM */
errorPlacement : function(error, element) {
error.appendTo(element.parent());
}
});
$("#save1").click(function() {
$("#form1").submit();
});
});
</script>
</html>

  使用Validate插件后,我们可直接根据表单元素的id或name值进行表单验证操作,而不必在表单元素内一些onclick、onchange事件,这使得页面更加干净、简洁,也使得我们的表单验证操作更一目了然。

  新技巧get√!!!over…

注:贴一个Email辅助输入JS,有兴趣的可以看一下

 /*==================email 辅助输入====================*/
var xfId,totalid,emailafter,emailbefor;
var cenPress = false;
/*
* email2输入框输入文字时触发并显示email辅助输入下拉框
*/
$(document).ready(function(){
$("#email2").focus(function(){ //email2获得焦点,dom写入email辅助输入层
$("#myEmail2").remove();//移除历史辅助信息
$(this).after("<div id='myEmail2' class='form-control' style='width:200px; height:auto; background:#fff; color:#6B6B66; position:absolute; left:"+$(this).get(0).offsetLeft+"px; top:"+($(this).get(0).offsetTop+$(this).height()+2)+"px; border:1px solid #ccc;z-index:5; '></div>");
if($("#myEmail2").html()==true){
$("#myEmail2").css("display","block");//显示
$(".newEmail").css("width",$("#myEmail2").width());//改变宽度
cenPress = true;
} else {
$("#myEmail2").css("display","none");//隐藏
cenPress = false;
}
}).keyup(function(){ //email2文本框输入时,触发,显示Email辅助输入
var press = $("#email2").val();
if(press!=""&&$.trim(press)==""){//判断是否输入空格
$("#emailSpan").html("<span style='font-size:13px;line-height:30px;color:red;'>请不要输入空格!</span>");
}
if ($.trim(press)!=""&& press!=null){//判断是否输入空格以外的值
var emailText = "";
var emailArray = new Array("@163.com","@qq.com","@126.com","@sina.com","@gmail.com","@yahoo.com","@hotmail.com","@foxmail.com");
totalid = emailArray.length;//获取array长度,并赋值给totalid
var emailS = "<div class='newEmail' style='width:200px;overflow:hidden;height:25px;line-height:25px; color:#6B6B66; '>"                 +"<font color='#D33025'>" + press + "</font></div>";
if(!(isEmail(press))){
for(var i=0; i<emailArray.length; i++) {
emailText = emailText + "<div class='newEmail' style='width:200px;color:#6B6B66;overflow:hidden;height:25px;"
                  +"line-height:25px;'><font color='#D33025'>" + press + "</font>" + emailArray[i] + "</div>";
}
} else {
emailbefor = press.split("@")[0];//@前的数据值
emailafter = "@" + press.split("@")[1];//@+@后的数据值
//循环显示拼接email辅助提示后的值
for(var i=0; i<emailArray.length; i++) {
var emailStr = emailArray[i];
if(emailStr.indexOf(emailafter) == 0) {
emailText = emailText + "<div class='newEmail' style='width:200px;height:25px;line-height:25px; "
            +"color:#6B6B66; overflow:hidden;'><font color='#D33025'>" + emailbefor + "</font>" + emailArray[i] + "</div>";
}
}
} //显示email辅助输入下拉框的数据
$("#myEmail2").html(emailS+emailText);
if($("#myEmail2").html()){
$("#myEmail2").css("display","block");
$(".newEmail").css("width",$("#myEmail2").width());
cenPress = true;
} else {
$("#myEmail2").css("display","none");
cenPress = false;
}
beforepress = press;
}
//无输入值不显示辅助输入框
if (press=="" || press==null){
$("#myEmail2").html("");
$("#myEmail2").css("display","none");
}
}); //鼠标悬浮时显示高亮效果
$(document).on("mouseover",".newEmail",function(){
$(".newEmail").css("background","#FFF");
$(this).css("background","#CACACB");
$(this).focus();
xfId = $(this).index();
}).on("click",".newEmail",function(){ //点击选中
var htmlVal = $(this).html();
htmlVal = htmlVal.replace(/<.*?>/g,"");
$("#email2").val(htmlVal); //根据所选内容,替换email2的值
$("#myEmail2").remove();//删除提示层
$("#email2").keyup();
}); //email选择文本框失去焦点时删除层
$(document).click(function(){
if(cenPress){
$("#myEmail2").remove();
cenPress = false;
if($("#emai2").focus()){
cenPress = false;
}
}
});
}) ;
//检查email邮箱,看是否输入@
function isEmail(str){
return str.indexOf("@") > 0?true:false;
}