惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
I
InfoQ
H
Hacker News: Front Page
D
Docker
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
博客园 - 【当耐特】
T
Tor Project blog
U
Unit 42
H
Heimdal Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Privacy & Cybersecurity Law Blog
PCI Perspectives
PCI Perspectives
美团技术团队
O
OpenAI News
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog

博客园 - yangjun

转:好用的抓取dump的工具-ProcDump 网页的栅格系统设计 jQuery 结合 Json 提交数据到Webservice,并接收从Webservice返回的Json数据 - yangjun JQuery 选择器、过滤器 普通程序员回顾2010 数据库从sql 2000迁移到SQL 2005遇到的问题 编写自文档化的代码 Top 10 steps to optimize data access in SQL Server. Part II C#六种集合性能比较 一个想法:把园子每月的精华文章制作成PDF文档 请问:哪里的空间申请较实惠 自定义“验证码”控件(转) 特性和属性 掌握ASP.NET之路:自定义实体类简介 深入浅出Attribute(中)——Attribute本质论 深入浅出Attribute(上)——Attribute本质论 (转) Head First IL中间语言--实例深入经典诠释(转) [转]CSS技巧:无懈可击的CSS圆角技术 C#的内存管理:堆栈、托管堆与指针 (转)
简单自定义实现jQuery验证
yangjun · 2008-03-13 · via 博客园 - yangjun

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

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

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

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

<%@ WebHandler Language="C#" Class="validateEmail" %>

using System;
using System.Web;
using System.Data.SqlClient;

public class validateEmail : IHttpHandler {
    
    
public void ProcessRequest (HttpContext context) {

        
if (context.Request.QueryString.Count != 0)
        
{
            
string email = context.Request.QueryString[0].Trim();
            context.Response.ContentType 
= "text/plain";
            SqlConnection conn 
= new SqlConnection("Server=localhost;User Id=sa;Password=;Database=XXX");
            SqlCommand sqlCmd 
= new SqlCommand("select count(*) from Clients where email=@email", conn);
            sqlCmd.Parameters.AddWithValue(
"@email", email);

            
try
            
{
                conn.Open();
                
int result = (int)sqlCmd.ExecuteScalar();
                context.Response.Write(
"{message:'"+result.ToString()+"'}"); //输出为JSON格式
            }

            
finally
            
{
                conn.Close();
            }

        }


    }

 
    
public bool IsReusable {
        
get {
            
return false;
        }

    }


}

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

js脚本代码:

    //给定需要验证的input添加 needValidate='true' 的属性对,然后选择他们,添加blur的事件函数。
    $("input[needValidate='true']").blur(function()
    
{
       
if(requireField(this))//首先客户端验证
       {
         
if(this.id == 'your_email')//如果是邮件则还进行ajax服务器端验证
         {
           $(
'#email_img').html("<img src='loading.gif' />");
           $.getJSON(
"validateEmail.ashx",{email:this.value},processValidateEmail);//getJSON获取服务器端的验证结果
         }

         
else
         
{
              $(
'#'+this.id+'_img').html("<img src='accept.gif' />");
              $(
'#'+this.id+'_error').html("");
         }

       }

    }

    )


});

//ajax验证完成后的处理函数
function processValidateEmail(data)
{
   
if(data.message == "0")//表示服务器端没有该邮箱地址
   {
       $(
'#your_email_img').html("<img src='accept.gif' />");
       $(
'#your_email_error').html("");
   }

   
else
   
{
      $(
'#your_email_img').html("<img src='exclamation.gif' />");
      $(
'#your_email_error').html("邮箱已被人注册,请更换重试!").attr("style","color:red;");
   }

}


//客户端验证函数
function requireField(o)
{
   var your_email 
= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   var your_name 
= /^(\w){4,20}|[^u4e00-u9fa5]{2,20}$/;
   var your_tel 
= /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/;
   var your_email_error 
= "请输入正确的邮箱格式!";
   var your_name_error 
= "请输入您的名字,不少于4个字符!";
   var your_tel_error 
= "请输入正确的电话号码格式!";
   
   
if(o.value.match(eval(o.id)))
   
{
      
return true;
   }

   
else
   
{
      $(
'#'+o.id+'_img').html("<img src='exclamation.gif' />");
      $(
'#'+o.id+'_error').html(eval(o.id+'_error')).attr("style","color:red;");
   }

   
return false;
}


//submit前的验证函数
function validate() {
    var biaozhi 
= true;
    $(
"input[needValidate='true']").each(function(i){
       
if(!requireField(this))
       
{ biaozhi = false; }
       }

    )
    
return biaozhi;
}

html须验证的表单代码:

<li><label for="your_name">你的姓名:</label>
    
<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>
<li><label for="your_email">你的邮箱:</label>
    
<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>
<li><label for="your_tel">你的电话:</label>
    
<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>
<li><label for="comment">相关信息:</label>
    
<input id="comment" name="comment" type="text" value="" /></li>