首页 > 技术文章 > 基于Jquery Validate 的表单验证

ylhssn 2014-10-31 17:00 原文

基于Jquery Validate 的表单验证

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

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

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

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

 1 <form action="XXXX.action"  method="post" onsubmit="return checkNull();">
 2   <p>
 3     <span class="pSpan">邮 箱:</span>
 4     <input type="text" id="userMail" maxLength="100" onclick="clearSpan2(this,'span7')" onchange="check(this,2,'span7')" />
 5     <span id="span7" style="color: red; font-size: 13px;"></span>
 6   </p>
 7   <p>
 8     <span class="pSpan">手机号:</span>
 9     <input type="text" id="userPhone" onchange="check(this,3,'span8')" onclick="clearSpan2(this,'span8')" />
10     <span id="span8" style="color:red;font-size:13px;"></span>
11   </p>
12   <p>
13     <input type="submit" value="确认" />
14     <input type="reset" value="重置" onclick="clearSpan()" />
15    </p>
16 </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 }
 1 // 验证数据格式
 2 function checkByRegExp(str, flag) {
 3   switch (flag) {
 4   case 2:
 5     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}$/);
 7     return reg.test(str);// 邮箱格式
 8     break;
 9   case 3:
11     var reg = new RegExp(/^0?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/);
13     return reg.test(str);// 手机号格式
14     break;
15   }
16 }

  采用传统的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插件

1 <script type="text/javascript" src="../jquery-ui-1.9.0/jquery-1.8.2.min.js"></script>
2 <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,有兴趣的可以看一下

 1 /*==================email 辅助输入====================*/
 2 var xfId,totalid,emailafter,emailbefor;
 3 var cenPress = false;
 4 /*
 5  * email2输入框输入文字时触发并显示email辅助输入下拉框
 6  */
 7 $(document).ready(function(){    
 8     $("#email2").focus(function(){ //email2获得焦点,dom写入email辅助输入层
 9         $("#myEmail2").remove();//移除历史辅助信息
10     $(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>");
11         if($("#myEmail2").html()==true){
12             $("#myEmail2").css("display","block");//显示
13             $(".newEmail").css("width",$("#myEmail2").width());//改变宽度
14             cenPress = true;
15         } else {
16              $("#myEmail2").css("display","none");//隐藏
17              cenPress = false;
18         }        
19     }).keyup(function(){ //email2文本框输入时,触发,显示Email辅助输入
20         var press = $("#email2").val();
21         if(press!=""&&$.trim(press)==""){//判断是否输入空格
22             $("#emailSpan").html("<span style='font-size:13px;line-height:30px;color:red;'>请不要输入空格!</span>");
23         }
24         if ($.trim(press)!=""&& press!=null){//判断是否输入空格以外的值
25         var emailText = "";            
26         var emailArray = new Array("@163.com","@qq.com","@126.com","@sina.com","@gmail.com","@yahoo.com","@hotmail.com","@foxmail.com");
27         totalid = emailArray.length;//获取array长度,并赋值给totalid
28             var emailS = "<div class='newEmail' style='width:200px;overflow:hidden;height:25px;line-height:25px; color:#6B6B66; '>"                 +"<font color='#D33025'>" + press + "</font></div>";
29             if(!(isEmail(press))){
30                 for(var i=0; i<emailArray.length; i++) {
31                     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>"; 32 } 33 } else { 34 emailbefor = press.split("@")[0];//@前的数据值 35 emailafter = "@" + press.split("@")[1];//@+@后的数据值 36 //循环显示拼接email辅助提示后的值 37 for(var i=0; i<emailArray.length; i++) { 38 var emailStr = emailArray[i]; 39 if(emailStr.indexOf(emailafter) == 0) { 40 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>"; 41 } 42 } 43 } 44 45 //显示email辅助输入下拉框的数据 46 $("#myEmail2").html(emailS+emailText); 47 if($("#myEmail2").html()){ 48 $("#myEmail2").css("display","block"); 49 $(".newEmail").css("width",$("#myEmail2").width()); 50 cenPress = true; 51 } else { 52 $("#myEmail2").css("display","none"); 53 cenPress = false; 54 } 55 beforepress = press; 56 } 57 //无输入值不显示辅助输入框 58 if (press=="" || press==null){ 59 $("#myEmail2").html(""); 60 $("#myEmail2").css("display","none"); 61 } 62 }); 63 64 65 //鼠标悬浮时显示高亮效果 66 $(document).on("mouseover",".newEmail",function(){ 67 $(".newEmail").css("background","#FFF"); 68 $(this).css("background","#CACACB"); 69 $(this).focus(); 70 xfId = $(this).index(); 71 }).on("click",".newEmail",function(){ //点击选中 72 var htmlVal = $(this).html(); 73 htmlVal = htmlVal.replace(/<.*?>/g,""); 74 $("#email2").val(htmlVal); //根据所选内容,替换email2的值 75 $("#myEmail2").remove();//删除提示层 76 $("#email2").keyup(); 77 }); 78 79 //email选择文本框失去焦点时删除层 80 $(document).click(function(){ 81 if(cenPress){ 82 $("#myEmail2").remove(); 83 cenPress = false; 84 if($("#emai2").focus()){ 85 cenPress = false; 86 } 87 } 88 }); 89 }) ; 90 //检查email邮箱,看是否输入@ 91 function isEmail(str){ 92 return str.indexOf("@") > 0?true:false; 93 }

 

推荐阅读