jQuery.Validate 使用例子

时间:2022-12-04 14:34:30

苦于验证的烦恼,所以需要学习一下jQuery.Validate,但一开始竟无从下手,看官方的例子也不明白(个人英语不行,理解能力也相当有限)。

看到http://www.cnblogs.com/kyo-yo/archive/2010/06/28/Use-jQueryValidate-To-Validate-Client.html的文章,对自己的理解有很大的帮助,但还是有点麻烦,我喜欢直来直往的说,傻瓜试的应用。所以,我想写下这些东西,供以后自己回看。

首先,建立一个最简单的例子。

页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="Web.register" %>

<!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>
    <link href="commonCss/index.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="commonCss/common.css" />
    <link rel="stylesheet" type="text/css" href="commonCss/register.css" /><link rel="stylesheet" type="text/css" href="commonCss/msgbox.css" /><script type="text/javascript" src="jquery_validate/jquery-1.5.2.js"></script>
    <script type="text/javascript" src="js/msgbox.js"></script>
    <script type="text/javascript" src="jquery_validate/jquery.validate1.js"></script>
    <script type="text/javascript" src="jquery_validate/jQuery.validate.message_cn.js"></script>
    <script type="text/javascript" src="jquery_validate/jquery.metadata.js"></script>
    <script type="text/javascript" src="jquery_validate/jquery.validate.extension.js"></script>
    <script type="text/javascript" src="jquery_validate/cmxforms.js"></script>
    <script type="text/javascript" src="js/register.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <!--头部start-->
    <div id="head">
        <div id="userInfo">
           <a href="login.aspx">登录</a>
             
           <a href="register.aspx">注册</a>
              
           <a href="#">找回密码</a>
        </div>
        <div id="titleUL">
           <div style="float:left;">微力量</div>
           <div id="headMenu">
              <ul>
                 <a href="index.aspx"><li>首页</li></a>
                 <a href="#"><li>功能介绍</li></a>
                 <a href="#"><li>日志</li></a>
                 <a href="#"><li>帮助</li></a>
                 <a href="#"><li>关于我们</li></a>
              </ul>
           </div>
        </div>
    </div>
    <!--头部end-->
    <!--中部start-->
    <div id="content" class="box">
         <div class="box" style="margin-bottom:10px; padding-left:90px;">
               <h1>立即注册</h1>
               已有账户,<a href="login.aspx" title="现在就去登录">现在登录</a>
          </div>
          <div id="RegisterInfo">
          <div class="box item">
               <div class="L">帐号:</div>
         <div class="R">
             <asp:TextBox ID="txtAccounts" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">密码:</div>
         <div class="R">
             <asp:TextBox ID="txtPass" TextMode="Password" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">确认密码:</div>
         <div class="R">
             <asp:TextBox ID="txtAgain" TextMode="Password" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">联系人:</div>
         <div class="R">
             <asp:TextBox ID="txtContacts" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">电话:</div>
         <div class="R">
             <asp:TextBox ID="txtPhone" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">手机:</div>
         <div class="R">
             <asp:TextBox ID="txtMobile" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
          <div class="box item">
               <div class="L">Email:</div>
         <div class="R">
             <asp:TextBox ID="txtEmail" CssClass="inputBox" runat="server"></asp:TextBox><span></span>
         </div>
          </div>
           <div class="box item">
               <div class="L">验证码:</div>
         <div class="R">
             <asp:TextBox ID="txtCode" CssClass="inputBox" runat="server"></asp:TextBox><span>
             <script type="text/javascript" language="JavaScript">
                        var numkey = Math.random();
                        numkey = Math.round(numkey * 10000);
                        document.write("<img src=\"../ValidateCode.aspx?k=" + numkey + "\" width=\"60\" onClick=\"this.src+=Math.random()\" title=\"图片看不清?点击重新得到验证码\" style=\"cursor:pointer;margin-bottom:-10px;\" height=\"30\" hspace=\"4\" />");
                        </script>
               </span>
         </div>
          </div>
          <div class="box item">
               <div class="L"></div>
         <div class="R">
             <asp:Button ID="btnInput" style="font-size:20px;" CssClass="btnGreen" 
                 runat="server" Text="注册" onclick="btnInput_Click" />
         </div>
          </div>
          </div>
          <div id="Pic">
              <img src="images/wxIntr.png" />
          </div>
          
    </div>
    <!--中部end-->
    <!--底部start-->
    <div id="footer">
    Copyright©2013 WeiLiLiang.COM All Rights Reserved 微力量 版权所有
隐私权政策 粤ICP备13008261号 
    </div>
    <!--底部end-->
    </form>
</body>
</html>

 

ValidateCode.asmx

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using BLL;

namespace Web.Service
{
    /// <summary>
    /// ValidateCode 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class ValidateCode : System.Web.Services.WebService
    {

        [WebMethod(EnableSession = true)]
        public AjaxClass CheckCode(string code)
        {
            AjaxClass ajaxClass = new AjaxClass();
            if (Session["ValidateCode"] != null)
            {
                if (Session["ValidateCode"].ToString() == code.ToUpper())
                {
                    ajaxClass.Msg = "验证成功。";
                    ajaxClass.Result = 1;
                }
                else
                {
                    ajaxClass.Msg = "验证码错误";
                    ajaxClass.Result = 0;
                }
            }
            else
            {
                ajaxClass.Msg = "验证码过时";
                ajaxClass.Result = 0;
            }
            return ajaxClass;

        }

        [WebMethod]
        public AjaxClass CheckLoginUser(string LoginUser)
        {
            AjaxClass ajaxClass = new AjaxClass();
            BusinessUserManager userManager = BusinessUserManager.GetInstrance();
            if (userManager.LoginUserIsUser(LoginUser))
            {
                ajaxClass.Msg = "此帐号已存在。";
                ajaxClass.Result = 0;
            }
            else
            {
                ajaxClass.Msg = "通过";
                ajaxClass.Result = 1;
            }
            return ajaxClass;

        }
    }
}

[Serializable]
public class AjaxClass
{
    public string Msg { get; set; }
    public int Result { get; set; }
}

消息样式

label.success
{
	background-image: url(/images/sign-up-form.png);
	background-repeat: no-repeat;
	background-position: -166px -15px;
	margin-left: 8px;
	padding-left: 20px;
	width: 16px;
	height: 18px;
	vertical-align: middle;
	font-size: 14px;
}
label.error
{
	background-image: url(/images/sign-up-form.png);
	background-repeat: no-repeat;
	background-position: -165px 3px;
	color: Red;
	margin-left: 8px;
	padding-left: 20px;
	width: 16px;
	height: 18px;
	vertical-align: middle;
	font-size: 14px;
}

register.js

jQuery.metadata.setType("attr", "validate");
var opts = null;
var isValidationGroup = false;

jQuery(document).ready(function() {
    InitRules();
    if (isValidationGroup) {
        if (opts != undefined || opts != null) {
            jQuery("#form1").validate(jQuery.extend(opts, {
                onsubmit: false
            }));
        } else {
            jQuery("#form1").validate({
                onsubmit: false
            });
        }
        InitValidationGroup();
    } else {
        if (opts != undefined || opts != null) {
            jQuery("#form1").validate(opts);
        } else {
            jQuery("#form1").validate();
        }
    }
});

function InitRules() {
    //code是asmx那边的参数名称
    var dataCode = {
        code: function() {
            return $("#txtCode").val();
        }
    };
    var remoteCode = GetRemoteInfo('/Service/ValidateCode.asmx/CheckCode', dataCode);
    
    var dataParam = {
        LoginUser: function() {
            return $("#txtAccounts").val();
        }
    };
    var remoteLoginUser = GetRemoteInfo('/Service/ValidateCode.asmx/CheckLoginUser', dataParam);
    
jQuery.validator.addMethod("TelValid", function(value, element)              {

                var  Telphone= /^0\d{2,3}-\d{5,9}|0\d{2,3}-\d{5,9}$/;
                return Telphone.test(value) || this.optional(element);

            }, "电话格式应为:区号-号码");
            jQuery.validator.addMethod("MobileValid", function(value, element) {
                var tel = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
                return tel.test(value) || this.optional(element);
            }, "请输入正确的手机号码格式");
    opts = {
        rules: {
            txtAccounts:{
               required: true,
               remote: remoteLoginUser
            },
            txtEmail: {
                required: true,
                email:true
            },
            txtPass: {
                required: true,
                minlength:6
            },
            txtAgain:{
                required: true,
                equalTo:"#txtPass"//注意:在这里,如果不引用上引号,在IE报找不到txtPass,花了两个小时才找到原因,不容易。
            },
            txtContacts: {
                required: true
            },
            txtPhone:{
                required:true,
                TelValid:true
            },
            txtMobile:{
                required:true,
                MobileValid:true
            },
            txtCode: {
                required: true,
                remote: remoteCode
            }
        },
        messages: {
            txtAccounts: {
                required: "请输入帐号"
            },
            txtEmail: {
                required: "请输入Email。"
            },
            txtPass: {
                required: "请输入密码。",
                minlength:"至少输入6位的密码。"
            },
            txtAgain: {
                required: "请输入确认密码。",
                equalTo:"密码不一致。"
            },
            txtContacts: {
                required: "请输入联系人。"
            },
            txtPhone:{
                required:"请输入电话号码。"
            },
            txtMobile:{
                required:"请输入手机号码"
            },
            txtCode: {
                required: "请输入验证码。"
            }
        }
        ,success: function(label) {
            label.html(" ").attr("class", "success").siblings("label").remove(); 
        },
        errorPlacement: function(error, element) {
            $(element).next("span").find(".success").remove();
            error.appendTo(element.next("span"));
        }
    }
}

页面控件后面加一对span标签,用于存放提示信息。

上面的验证js中success和errorPlacement主要是兼容各个各个浏览器,验证成功或失败信息显示的位置。

jquery.js必须是jquery-1.5.2.js版本,否则在IE6下不行。听说jquery版本要和jquery validate的版本匹配才行。我也是下载别人的jquery validate也不知道是那个版本。

但是测试过,这个版本的jquery validate能用。管他呢,能用就行。

 

jquery validate下载