来源 简单自定义实现jQuery验证

[ 2008-3-14 10:40:24 | 作者: 一线风 | 阅读:1465 | 评论:0 | 天气: sunny | 心情: normal ]
Font Size: Large | Medium | Small

分两种情况验证,一是直接使用本地验证,二是ajax到服务器验证。

我现在需要验证:用户名,邮箱,电话 三个input(text),用户名、电话号码只需要本地验证格式,只要匹配给定的正则表达式即可,而邮箱首先在本地验证格式,符合格式则ajax到服务器验证是否已被注册,如果被注册了则不能通过验证。

对于每个input后面跟随三种状态,分别表示验证通过、验证未通过、正在提交服务器验证,当未通过验证时,还出示提示信息。

首先设计服务器端的邮箱验证,这里使用.ashx 文件。

转自:http://www.cnblogs.com/somesongs/archive/2008/03/13/1103068.html

C#代码
  1. <%@ WebHandler Language="C#" Class="validateEmail" %>   
  2.   
  3. using System;   
  4. using System.Web;   
  5. using System.Data.SqlClient;   
  6.   
  7. public class validateEmail : IHttpHandler {   
  8.        
  9.     public void ProcessRequest (HttpContext context) {   
  10.   
  11.         if (context.Request.QueryString.Count != 0)   
  12.         {   
  13.             string email = context.Request.QueryString[0].Trim();   
  14.             context.Response.ContentType = "text/plain";   
  15.             SqlConnection conn = new SqlConnection("Server=localhost;User Id=sa;Password=;Database=XXX");   
  16.             SqlCommand sqlCmd = new SqlCommand("select count(*) from Clients where email=@email", conn);   
  17.             sqlCmd.Parameters.AddWithValue("@email", email);   
  18.   
  19.             try  
  20.             {   
  21.                 conn.Open();   
  22.                 int result = (int)sqlCmd.ExecuteScalar();   
  23.                 context.Response.Write("{message:'"+result.ToString()+"'}"); //输出为JSON格式   
  24.             }   
  25.             finally  
  26.             {   
  27.                 conn.Close();   
  28.             }   
  29.         }   
  30.   
  31.     }   
  32.     
  33.     public bool IsReusable {   
  34.         get {   
  35.             return false;   
  36.         }   
  37.     }   
  38.   
  39. }  


接下来实现客户端的html,添加对JQuery的引用

js脚本代码:

JavaScript代码
  1.   //给定需要验证的input添加 needValidate='true' 的属性对,然后选择他们,添加blur的事件函数。   
  2.     $("input[needValidate='true']").blur(function()   
  3.     {   
  4.        if(requireField(this))//首先客户端验证   
  5.        {   
  6.          if(this.id == 'your_email')//如果是邮件则还进行ajax服务器端验证   
  7.          {   
  8.            $('#email_img').html("<img src='loading.gif' />");   
  9.            $.getJSON("validateEmail.ashx",{email:this.value},processValidateEmail);//getJSON获取服务器端的验证结果   
  10.          }   
  11.          else  
  12.          {   
  13.               $('#'+this.id+'_img').html("<img src='accept.gif' />");   
  14.               $('#'+this.id+'_error').html("");   
  15.          }   
  16.        }   
  17.     }   
  18.     )   
  19.   
  20.   
  21. });   
  22.   
  23. //ajax验证完成后的处理函数   
  24. function processValidateEmail(data)   
  25. {   
  26.    if(data.message == "0")//表示服务器端没有该邮箱地址   
  27.    {   
  28.        $('#your_email_img').html("<img src='accept.gif' />");   
  29.        $('#your_email_error').html("");   
  30.    }   
  31.    else  
  32.    {   
  33.       $('#your_email_img').html("<img src='exclamation.gif' />");   
  34.       $('#your_email_error').html("邮箱已被人注册,请更换重试!").attr("style","color:red;");   
  35.    }   
  36. }   
  37.   
  38. //客户端验证函数   
  39. function requireField(o)   
  40. {   
  41.    var your_email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;   
  42.    var your_name = /^(\w){4,20}|[^u4e00-u9fa5]{2,20}$/;   
  43.    var your_tel = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;   
  44.    var your_email_error = "请输入正确的邮箱格式!";   
  45.    var your_name_error = "请输入您的名字,不少于4个字符!";   
  46.    var your_tel_error = "请输入正确的电话号码格式!";   
  47.       
  48.    if(o.value.match(eval(o.id)))   
  49.    {   
  50.       return true;   
  51.    }   
  52.    else  
  53.    {   
  54.       $('#'+o.id+'_img').html("<img src='exclamation.gif' />");   
  55.       $('#'+o.id+'_error').html(eval(o.id+'_error')).attr("style","color:red;");   
  56.    }   
  57.    return false;   
  58. }   
  59.   
  60. //submit前的验证函数   
  61. function validate() {   
  62.     var biaozhi = true;   
  63.     $("input[needValidate='true']").each(function(i){   
  64.        if(!requireField(this))   
  65.        { biaozhi = false; }   
  66.        }   
  67.     )   
  68.     return biaozhi;   
  69. }  

html须验证的表单代码:

XML/HTML代码
  1. <li><label for="your_name">你的姓名:</label>  
  2.     <input name="your_name" id="your_name" type="text" needValidate="true" value="" /><span id="your_name_img"></span><div id="your_name_error"></div></li>  
  3. <li><label for="your_email">你的邮箱:</label>  
  4.     <input name="your_email" id="your_email" type="text" needValidate="true" value="" /><span id="your_email_img"></span><div id="your_email_error"></div></li>  
  5. <li><label for="your_tel">你的电话:</label>  
  6.     <input name="your_tel" id="your_tel" type="text" needValidate="true" value="" /><span id="your_tel_img"></span><div id="your_tel_error"></div></li>  
  7. <li><label for="comment">相关信息:</label>  
  8.     <input id="comment" name="comment" type="text" value="" /></li>  

 

以下为javascript正则表达式的参考:
http://www.ccvita.com/index.php/61.html
http://www.cnblogs.com/westlake/articles/388873.html

分类:C#/.Net
Tag: C# ajax jquery 验证