验证控件

摘要
 
ASP.NET功能强大的一种体现就是具有丰富的Web控件,这里我们谈谈其中的一种—验证控件。它总结了各种Web数据校验方式,设计成了今天这种通用的ASP.NET控件形式。

目录
 
1. 验证控件简介
2. 验证控件的使用方法
3. 小结

1. 验证控件简介
 
顾名思义,验证控件就是校验用户输入数据正确性的控件,如用户在文本框中输入数据后,便显示一条提示信息,表明了校验的数据是不合法的。验证过程既可以在服务器上执行,也可以在客户机上执行,在客户端运行的校验代码是数据提交之前被执行的,因此可以提高程序的性能。ASP.NET的验证控件可以进行多种校验,如数据范围检查、数据间的比较和自定义校验等等,下面的内容将会逐一介绍这些验证控件。
ASP.NET公有六种验证控件,分别如下: 
控件名 功能描叙
RequiredFieldValidator(必须字段验证) 用于检查是否有输入值
CompareValidator(比较验证) 按设定比较两个输入
RangeValidator(范围验证) 输入是否在指定范围
RegularExpressionValidator(正则表达式验证) 正则表达式验证控件
CustomValidator(自定义验证) 自定义验证控件
ValidationSummary(验证总结) 总结验证结果

2. 验证控件的使用方法
 
① RequiredFieldValidator控件
当页面上的控件要求必须输入数据时,RequiredFieldValidator就起作用了,ControlToValidate属性选择需要验证的控件,而ErrorMessage属性则是校验不合法后显示的错误提示信息。
ControlToValidate:表示要进行检查控件ID;
ErrorMessage:表示当检查不合法时,出现的错误信息;
Display:错误信息的显示方式;Static表示控件的错误信息在页面中占有肯定位置;Dymatic表示控件错误信息出现时才占用页面控件;None表示错误出现时不显示,但是可以在ValidatorSummary中显示;
占位符:表示Display为Static时,错误信息占有"占位符"那么大的页面空间;
<HTML>
  <HEAD>
    <title>RequiredFieldValidator Example</title>
  </HEAD>
<BODY>
  <form id="Form1" runat="server">
    Name:
    <asp:TextBox id="TextBox1" runat="server" ></asp:TextBox>
    <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" 
ErrorMessage="Please enter your name" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
    <asp:Button id="Button1"  runat="server" Text="Button"></asp:Button>
  </form>
</BODY>
</HTML>
②CompareValidator控件
CompareValidator控件是用来比较两个输入控件之间的数据一致性的,同时也可以用来校验控件中内容的数据类型:如整形、字符串型等。ControlToCompare和ControlToValidate属性用来设置进行比较的两个控件。
Type表示要比较的控件的数据类型;
Operator表示比较操作(也就是刚才说的为什么比较不仅仅是"相等"的原因),这里,比较有7种方式;
其他属性和RequiredFieldValidator相同;
在这里,要注意ControlToValidate和ControlToCompare的区别,如果operate为GreateThan,那么,必须ControlToCompare大于ControlToValidate才是合法的。
<HTML>
  <HEAD>
    <title>CompareValidator Example</title>
  </HEAD>
<BODY>
  <form id="Form1" runat="server">
    <P>Password:
    <asp:TextBox id="txtPwd" runat="server" TextMode="Password"></asp:TextBox><BR>
    Confirm:
    <asp:TextBox id="TxtCfm" runat="server" TextMode="Password"></asp:TextBox></P>
    <P>
    <asp:Button id="Button2" runat="server" Text="Button"></asp:Button>
    <asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="Password Error!" 
     ControlToValidate="TxtCfm" ControlToCompare="txtPwd"></asp:CompareValidator></P>
  </form>
</BODY>
</HTML>
③RangeValidator控件
RangeValidator控件可以用来判断用户输入的值是否在某一特定范围内,属性MaximumValue和MinimumValue用来设定范围的最大和最小值。
<HTML>
  <HEAD>
    <title>RangeValidator Example</title>
  </HEAD>
<BODY>
  <form id="Form1" runat="server">
  <P>Age:
  <asp:TextBox id="TxtAge" runat="server"></asp:TextBox>
  <asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TxtAge" 
   ErrorMessage="Age Error!" MaximumValue="99" MinimumValue="1"></asp:RangeValidator></P>
  </form>
</BODY>
</HTML>
④RegularExpressionValidator控件
RegularExpressionValidator控件可以判断用户输入的表达式是否正确,如电话号码、邮编、URL等,ControlToValidate属性选择需要验证的控件,ValidationExpression属性则编写需要在ValidationExpression中,不同的字符表示不同的含义:
  "."表示任意字符;
  "*"表示和其他表达式一起,表示容易组合;
  "[A-Z]"表示任意大写字母;
  "\d{}“\d”指定输入的值是一个数字,{}表示已指定数据类型的出现次数;
"\w"表示允许输入任何值;
"[]"检查输入的值是否与括号中的值之一相匹配;
  注意,在以上表达式中,引号不包括在内;
举例:
正则表达式:".*[A-Z]"表示数字开头的任意字符组合其后接一个大写字母。
<HTML>
  <HEAD>
    <title>RegularExpressionValidator Example</title>
  </HEAD>
<BODY>
  <form id="Form1" runat="server">
  <P>Postal Code:
  <asp:TextBox id="TxtPostalCode" runat="server"></asp:TextBox>
  <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" 
       ControlToValidate="TxtPostalCode" ErrorMessage="Postal Code Error!"    
       ValidationExpression="\d6}"></asp:RegularExpressionValidator></P>
  </form>
</BODY>
</HTML>
⑤CustomValidator控件
CustomValidator控件用于执行用户自定义的验证,这种校验既可以是服务器端的也可以是客户端的,下面的代码就是使用客户端验证邮编的例子。
<HTML>
  <HEAD>
    <title>CustomValidator Example</title>
  </HEAD>
<BODY>
  <form id="Form1" runat="server">
    <P>Postal Code:
    <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
    <asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1"  
         ErrorMessage="CustomValidator"  ClientValidationFunction="ClientValidate">
    </asp:CustomValidator></P>
  </form>
</BODY>
</HTML>
<script language="vbscript">
   Sub ClientValidate(source, arguments)
      If isnumeric(arguments.Value ) and len(arguments.Value)=6 Then
         arguments.IsValid=true
      Else
         arguments.IsValid=false
      End If
   End Sub
</script>
⑥ValidationSummary控件
这个控件会将页面中所有的校验错误输出为一个列表,列表的显示方式由DisplayMode属性设置。
HeadText相当于表的HeadText
DisplayMode表示错误信息显示方式:
List相当于HTML中的<BR>;
BulletList相当于HTML中的<LI>;
SingleParegraph表示错误信息之间不作如何分割
<HTML>
  <HEAD>
    <title>ValidationSummary Example</title>
  </HEAD>
<body>
  <form id="Form1" runat="server">
  <P>Age:
  <asp:TextBox id="TxtAge" runat="server"></asp:TextBox>
  <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
 ControlToValidate="TxtAge" ErrorMessage="Age Error!" Display="None"></asp:RequiredFieldValidator><BR>
  Postal Code:
  <asp:TextBox id="TxtPostalCode" runat="server"></asp:TextBox>
  <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" 
ControlToValidate="TxtPostalCode" ErrorMessage="Postal Code Error!" 
Display="None"></asp:RequiredFieldValidator></P>
  <P>
  <asp:Button id="Button1" runat="server" Text="Button"></asp:Button></P>
  <P>
  <asp:ValidationSummary id="ValidationSummary1" runat="server" 
   HeaderText="You must enter a value in the following fields:"></asp:ValidationSummary></P>
  </form>
</body>
</HTML>

3. 小结
 
以上内容仅是ASP.NET验证控件的简单介绍,使用这些控件熟练后便可以缩短开发时间,更能够省去大量的编写JavaScript的工作。
Page.IsValid
在ASP.Net中,为了方便表单的验证,提供了验证控件来完成表单输入数据的验证。问题的根源是对于asp:Button控 件,点击的时候是默认先进行表单的验证的。
有的朋友希望在表单里有两个按钮,其中有的按钮执行的操作和表单本身无关,不需要验证,但也默认必须进行验证,对 程序设计上造成不少烦恼。
解决方法:在需要验证的时候,可以手工调用验证代码:验证控件.Validate()或者Page.Validate()进行验证。
*****************************************
完整的验证方式

//default.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Untitled Page</title>
<style type="text/css">
.style1
{
width:
95%;
height: 216px;
}
.style5
{
}
.style6
{
width: 57px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<div style=" width: 500px; height:500px; background-color:Silver; text-align:left; margin-top: 20; padding: 10px 0px 0px 30px; margin-top:4%">

<table class="style1">
<tr>
<td class="style6">
<label for="txt_username">用户名: </label>
</td>
<td class="style5">
<asp:TextBox ID="txt_username" runat="server" Width="209px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="validator_rqeField_username" runat="server"
ControlToValidate
="txt_username" Display="Dynamic" ErrorMessage="用户名不能为空"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="validator_custom_username" runat="server"
ErrorMessage
="用户名已存在" ControlToValidate="txt_username"></asp:CustomValidator>
</td>
</tr>
<tr>
<td class="style6">
<label for="txt_password">密 码: </label>
</td>
<td class="style5">
<asp:TextBox ID="txt_password" runat="server" Width="209px" TextMode="Password"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="validator_rqeField_password" runat="server"
ControlToValidate
="txt_password" ErrorMessage="密码不能为空"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style6">
<label for="txt_confirm">确 认: </label>
</td>
<td class="style5">
<asp:TextBox ID="txt_confirm" runat="server" Width="209px" TextMode="Password"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="validator_rqe_confirm" runat="server"
Display
="Dynamic" ErrorMessage="确认密码不能为空" ControlToValidate="txt_confirm"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="validator_compto_conpass" runat="server"
ControlToCompare
="txt_password" ControlToValidate="txt_confirm"
Display
="Dynamic" ErrorMessage="密码不一致"></asp:CompareValidator>
</td>
</tr>
<tr>
<td class="style6">
<label for="txt_email">邮 箱: </label>
</td>
<td class="style5">
<asp:TextBox ID="txt_email" runat="server" Width="209px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="validator_rqeField_email" runat="server"
ControlToValidate
="txt_email" Display="Dynamic" ErrorMessage="邮箱不能为空"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="validator_regx_email" runat="server"
ControlToValidate
="txt_email" Display="Dynamic" ErrorMessage="邮件格式错误"
ValidationExpression
="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style6">
<label for="txt_birth">生 日: </label>
</td>
<td class="style5">
<asp:TextBox ID="txt_birth" runat="server" Width="209px"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="validator_range_birth" runat="server"
ControlToValidate
="txt_birth" ErrorMessage="日期格式错误" Type="Date"></asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style6">
验证码:
</td>
<td class="style5" colspan="2">
<asp:Image ID="Image1" runat="server" ImageUrl="~/DynamicCode.ashx"/>
</td>
</tr>
<tr>
<td class="style6">
输入验证码:
</td>
<td class="style5" colspan="2">
<asp:TextBox ID="txt_dcode" runat="server" Width="210px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage
="验证码不能为空" Display="Dynamic" ControlToValidate="txt_dcode"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="Validator_Dcode" runat="server"
ErrorMessage
="验证码错误" ControlToValidate="txt_dcode" Display="Dynamic"
onservervalidate
="Validator_Dcode_ServerValidate"></asp:CustomValidator>
</td>
</tr>
<tr>
<td colspan="3">
<asp:LinkButton ID="lbtn_reguser" runat="server" onclick="lbtn_reguser_Click">注 册</asp:LinkButton>
<asp:LinkButton ID="ltbn_forgetpass" runat="server">忘记密码?</asp:LinkButton>
</td>
</tr>
</table>

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

 

//default.aspx.cs代码

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

publicpartialclass _Default : System.Web.UI.Page
{
protectedvoid Page_Init(object sender, EventArgs e)
{
this.validator_range_birth.MaximumValue = DateTime.Now.ToShortDateString();
this.validator_range_birth.MinimumValue = DateTime.Now.AddYears(-150).ToShortDateString();
}

protectedvoid Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//this.Validate(); //手动调用验证方法
}

}
protectedvoid lbtn_reguser_Click(object sender, EventArgs e)
{
if (this.IsValid) //当所有页面对象验证通过后, 将设置Page的IsValid属性, 验证通过
{
DAL.CalendarUser calendaruser
=new DAL.CalendarUser();

//初始birthday为空, 当串不为空时转换
DateTime? birthday =null;
if (!string.IsNullOrEmpty(this.txt_birth.Text))
{
birthday
= DateTime.Parse(this.txt_birth.Text);
}

//int a = calendaruser.CreateUser(this.txt_username.Text, this.txt_password.Text, this.txt_email.Text, birthday);
int exist = calendaruser.CreateUserByProc(this.txt_username.Text, this.txt_password.Text, this.txt_email.Text, birthday);

if (exist !=0)
{
this.validator_custom_username.IsValid =false; //这里使用验证控件上的IsValid属性
}
}
}
protectedvoid Validator_Dcode_ServerValidate(object source, ServerValidateEventArgs args)
{
//每次复位Validator状态
args.IsValid =false;

#region Cookie
//HttpCookie hc = this.Request.Cookies["Dcode"];
//if (hc != null)
//{
// string rqtcode = hc.Value.ToString();
////if(rqtcode == args.Value)
// if (rqtcode == this.txt_dcode.Text)
// {
// args.IsValid = true; //这里必须用args.IsValid, 不能用this.validator_dcode.isvalid = true, 因为最后args.IsValid会覆盖掉this.validator_dcode.IsValid, 分析在最后
// }
//}
//else
//{
// args.IsValid = false;
//}
#endregion

#region Session
if (this.Session["Dycode"] !=null)
{
string num =this.Session["Dycode"] asstring;
if (num ==this.txt_dcode.Text)
{
args.IsValid
=true;
}
else
{
args.IsValid
=false;
}
}

#endregion
}
}

 

//DynamicCode.ashx代码

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

using System;
using System.Web;

//使用Session记得在ashx中, 添加IRequiresSessionState的接口, 而aspx文件默认就是支持的
publicclass DynamicCode : IHttpHandler,System.Web.SessionState.IRequiresSessionState {

publicvoid ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
context.Response.ContentType ="image/jpeg";

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

//随机数生成器
Random ran =new Random();
int rannum = ran.Next(10000, 100000);

//创建位图文件
System.Drawing.Bitmap bitmap =new System.Drawing.Bitmap(300, 80);

//在位图文件上画画, 需要创建与图片画板相关的画图器
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
//用Graphic对象清空背景
g.Clear(System.Drawing.Color.DarkGreen);

//花矩形框
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Brushes.Blue,3),0,0,bitmap.Width-1,bitmap.Height-1);

//StringFormat对象, 用来保存数字位置, 在数字矩形的绘图区域中
System.Drawing.StringFormat sf =new System.Drawing.StringFormat();
sf.Alignment
= System.Drawing.StringAlignment.Center;
sf.LineAlignment
= System.Drawing.StringAlignment.Center;

//画数字, RectangleF用来确定显示数字的矩形区域
g.DrawString(rannum.ToString(),
new System.Drawing.Font("黑体", 50),
System.Drawing.Brushes.Black,
new System.Drawing.RectangleF(0, 0, bitmap.Width, bitmap.Height),
sf);

//画横线
for (int i =0; i <80; i++)
{
g.DrawLine(
new System.Drawing.Pen(System.Drawing.Brushes.Black),
ran.Next(
0, bitmap.Width),
ran.Next(
0, bitmap.Height),
ran.Next(
0, bitmap.Width),
ran.Next(
0, bitmap.Height));
}

//将数字保存到Cookie中
//HttpCookie hc = new HttpCookie("Dcode");
//hc.Value = rannum.ToString();
//context.Response.Cookies.Add(hc); //保存到cookie中去, 但是没有页面对象, 所以需要通过context

//将数字保存到Session中
context.Session["DyCode"] = rannum.ToString();
}

//保存图片到response, 注意: 这里是一般处理程序, 没有页面对象, 所以只能用context
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}

publicbool IsReusable {
get {
returnfalse;
}
}

}
posted @ 2012-04-03 17:17  烧点饭  阅读(589)  评论(0编辑  收藏  举报