jQuery表单验证插件

时间:2022-01-15 14:26:18

      是不是感觉验证表单输入的有效性时会做很多重复劳动呢.那让我们来写一个简单的jQuery插件来简化我们的工作吧>>
代码下载地址: http://files.cnblogs.com/qindgfly/jquery-checkform.rar


JS文件
/* jQuery.checkform.js
 *
 * check type:
 *  mustInput
 *  mustMoreThan
 *  mustLessThan
 *  mustEqualTo
 *  mustEmail
 *  mustInt
 *  mustFloat
 *  mustSelect
 *  mustCheck
 *  mustRadio:
 *  mustRegular
 *
 */
 
jQuery.extend({ 
    options: {
        ctrls: [ ],//controls to check        
        success: function() { return; },//When check success,you can do something,such as submit a ajax request
        failed:  function(msg, id){ jQuery.clewMsg(msg, id); } //when check faild               
    },
 
 clewMsg: function(msg, id){
     alert(msg);
 },
 
 checkForm: function(o){ 
  o = jQuery.extend({},jQuery.options,o);
  
     var isok = true;
    
    
     var flashPrompt = function(ctr){
   var i = 0;   
   var intervalid = setInterval(function(){       
    jQuery("#"+ctr.id).toggleClass('warning');
    if(i++ > 2){
     clearInterval(intervalid);
     jQuery("#"+ctr.id).addClass('warning');
    }
   }, 100);   
  }; 
  
     //check failed, we alert a message, and change the control's style
     var fail = function(ctr){
             isok = false;
                o.failed(ctr.msg, ctr.id);
                flashPrompt(ctr);
                jQuery("#"+ctr.id).focus();
                return false;
         }
    
     //check success, we change the control to its original style
     var succ = function(ctr){
             jQuery("#"+ctr.id).removeClass('warning');
             return true;
         }
    
     //regular express check
     var checkRegularExpression = function(val, expression){
             if(val != "")
                {
                    var matchArray = val.match(expression);
                    if (matchArray == null)return false;else return true;
                }
                else return true;
         }
           
  jQuery.each(o.ctrls, function(i, ctr){
      switch(ctr.type)
      {
          case "mustInput":   if(jQuery("#"+ctr.id).val() == "")return fail(ctr); else return succ(ctr);
          case "mustMoreThan":if(jQuery("#"+ctr.id).val().length < ctr.par)return fail(ctr); else return succ(ctr);
          case "mustLessThan":if(jQuery("#"+ctr.id).val().length > ctr.par)return fail(ctr); else return succ(ctr);
          case "mustEqualTo": if(jQuery("#"+ctr.id).val() != jQuery("#"+ctr.par).val())return fail(ctr);else return succ(ctr);
          case "mustEmail":   if(!checkRegularExpression(jQuery("#"+ctr.id).val(), /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/))return fail(ctr);else return succ(ctr);
                case "mustInt":     if(!checkRegularExpression(jQuery("#"+ctr.id).val(), /^[0-9]*jQuery/))return fail(ctr);else return succ(ctr);
                case "mustFloat":   if(!checkRegularExpression(jQuery("#"+ctr.id).val(), /^[0-9]+\.{0,1}[0-9]{0,2}jQuery/))return fail(ctr);else return succ(ctr);
          case "mustSelect":  if(jQuery("#"+ctr.id).val() == ctr.par)return fail(ctr); else return succ(ctr);
          case "mustCheck":   if(!jQuery("#"+ctr.id).attr("checked"))return fail(ctr); else return succ(ctr);
          case "mustRadio":   if(jQuery("input[type='radio'][name='"+ctr.id+"']:checked").length<1)return fail(ctr); else return succ(ctr);
          case "mustRegular": if(!checkRegularExpression(jQuery("#"+ctr.id).val(), ctr.par))return fail(ctr);else return succ(ctr);
      }
      });
  
  
  if(isok) o.success();
 } 
});



调用:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Test_JqueryPlus_jquery_checkform_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
   
    <style type="text/css">
        .warning-normal
        {
            border: 1px solid #ccc;
        }
   
        .warning
        {
            border: 1px solid red;
        }
    </style>
   
    <script src="../jquery-1.2.6.js" type="text/javascript"></script>
    <script type="text/javascript" src="jquery.checkform.js"></script>
    <script type="text/javascript">
        jQuery(function($){
            jQuery("input,select,textarea").addClass("warning-normal");
        });
   
   
        function checkform()
        {
            jQuery.checkForm({
                ctrls: [                                  
                    {id: "txtUserName",type:"mustInput", par:"",msg: "please input your user name"},
                    {id: "txtPassword",type:"mustInput", par:"",msg: "please input your password"},
                    {id: "txtPassword",type:"mustMoreThan", par:"3", msg: "length of password must more than 3"},
                    {id: "txtPassword",type:"mustLessThan", par:"12", msg: "length of password less more than 12"},                   
                    {id: "txtPasswordAgain",type:"mustEqualTo", par:"txtPassword", msg: "password not math"},
                    {id: "txtEmail",type:"mustEmail", par:"", msg: "the email you input is invalid!"},
                    {id: "rdoSex",type:"mustRadio", par:"", msg: "select sex!"},    
                    {id: "txtTelephone",type:"mustEmail", par: /(\(\d{3}\)|\d{3}-)?\d{8}/, msg: "the telephone no. you input is invalid!"},
                    {id: "txtAge",type:"mustInt", par:"", msg: "age can only be integer!"},
                    {id: "txtWeight",type:"mustFloat", par:"", msg: "weight can only be float!"},
                    {id: "selCountry",type:"mustSelect", par:"0", msg: "please select your country!"},
                    {id: "txtRemark",type:"mustInput", par:"",msg: "please input remark"},
                    {id: "chkAgree",type:"mustCheck", par:"", msg: "please check to agree our terms!"}                   
                    ],
                success: function(){
                    $("#divmsg").html("");
                    $("#divmsg").hide();
                    alert("form check success,now we will commit our data!");                                      
                    },
                failed: function(msg){ 
                    $("#divmsg").html(msg);
                    $("#divmsg").show(); 
                    }
                });
        }
    </script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="divmsg" style="border-right: deepskyblue thin solid; display:none; margin:0; padding:0; border-top: deepskyblue thin solid;
            border-left: deepskyblue thin solid; width: 452px; color: #3300ff; border-bottom: deepskyblue thin solid;
            height: 27px">
        </div>
        <table style="width: 455px">
            <tr>
                <td colspan="2">
                    Jion to us</td>
            </tr>
            <tr>
                <td>
                    username:&nbsp;</td>
                <td>
        <input id="txtUserName" type="text" /></td>
            </tr>
            <tr>
                <td>
                    password:</td>
                <td>
        <input id="txtPassword" type="password" /></td>
            </tr>
            <tr>
                <td>
                    and once again?&nbsp;
                    <br />
                </td>
                <td>
                    <input id="txtPasswordAgain" type="text" /></td>
            </tr>
            <tr>
                <td>
                    and your sex?</td>
                <td>
                    <input id="Radio1" type="radio" name="rdoSex"/>
                    男
                    <input id="Radio2" type="radio" name="rdoSex" />
                    女</td>
            </tr>
            <tr>
                <td>
                    your telephone:</td>
                <td>
                    <input id="txtTelephone" type="text" /></td>
            </tr>
            <tr>
                <td>
                    your email:</td>
                <td>
                    <input id="txtEmail" type="text" /></td>
            </tr>
            <tr>
                <td>
                    your age:</td>
                <td>
                    <input id="txtAge" type="text" /></td>
            </tr>
            <tr>
                <td>
                    your weight:</td>
                <td>
                    <input id="txtWeight" type="text" /></td>
            </tr>
            <tr>
                <td>
                    country:</td>
                <td>
        <select id="selCountry">
            <option value="0">select</option>
            <option value="1">中国</option>
            <option value="2">美国</option>
            <option value="3">英国</option>           
        </select>
                </td>
            </tr>
            <tr>
                <td>
                    remark:</td>
                <td>
        <textarea id="txtRemark" cols="20" rows="2"></textarea></td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
        <input id="chkAgree" type="checkbox" />I agree all the terms.</td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
        <input id="Button1" type="button" value="check form" onclick="checkform()" /></td>
            </tr>
        </table>
    </div>

    </form>
</body>
</html>

界面预览:
jQuery表单验证插件

是不是代码减少了很多呢,验证不成功时文本框还有动画效果哦..