验证控件,net轻松打造功能完备的分页技术10bet手机官网:
分类:多线程

  RangeValidator 服务器控件测量检验输入值是不是坐落于给定的界定内。RangeValidator 使用
八个键属性试行验证。ControlToValidate 富含要表达的值。MinimumValue 和 
MaximumValue 定义有效限定的最小值和最大值。本例彰显怎么行使 RangeValidator 控
件。 
<%@ Page clienttarget=downlevel %>

用过asp开垦过web程序的人都知道,分页让asp程序猿是风度翩翩件非常讨厌的事,作者在这里就来讲说用asp.net轻便创设的分页本领.

摘要

<html>
<head> 
    <script language="C#" runat="server">
        void Button1_Click(Object sender, EventArgs e) {
           rangeValInteger.Validate();
           if (rangeValInteger.IsValid) {
               lblOutput1.Text = "结果:有效!";
           } else {
               lblOutput1.Text = "结果:无效!";
           }

先是步大家在vs.net新建项目,这几个笔者不说了,你自个儿解决啊,笔者在这里地关键贴出首要的代码.

 

           rangeValDate.Validate();
           if (rangeValDate.IsValid) {
               lblOutput2.Text = "结果:有效!";
           } else {
               lblOutput2.Text = "结果:无效!";
           }

1.webform1.aspx

ASP.NET成效强大的风度翩翩种显示就是兼具丰硕的Web控件,这里大家探讨在那之中的生龙活虎种—验证控件。它总结了各个Web数据校验形式,设计成了几天前这种通用的ASP.NET控件情势。

           rangeValString.Validate();
           if (rangeValString.IsValid) {
               lblOutput3.Text = "结果:有效!";
           } else {
               lblOutput3.Text = "结果:无效!";
           }

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="page.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
  <title>WebForm1</title>
  <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="" name="vs_targetSchema">
  </HEAD>
<body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <table align="center">
    <tr>
     <td style="HEIGHT: 104px" colspan=2><asp:datagrid id="DataGrid1" runat="server" PageSize="5" Font-Size="8pt" Font-Names="Verdana" BorderWidth="1px" BackColor="#FFE0C0" BorderColor="#FFC080" HorizontalAlign="Center" CellPadding="3" AllowPaging="True" Height="152px" Width="700px">
<AlternatingItemStyle BackColor="Linen">
</AlternatingItemStyle>


           if (Page.IsValid) {
              lblOutput.Text = "结果:页有效!";
           } else {
              lblOutput.Text = "结果:页无效!";
           }
        }
   </script>
</head>
<body>
    <h3><font face="宋体">RangeValidator 示例</font></h3>
    <p>
    <form runat="server">
      <table bgcolor="#eeeeee" cellpadding=10>
      <tr valign="top">
        <td>
            <h5><font face="钟鼓文">要反省的值:</font></h5>
            <asp:TextBox id="txtComp1" runat="server"/>
        </td>
        <td>
            <h5><font face="陶文">数据类型:整型最小值 (1卡塔尔,最大值 (10卡塔尔
</font></h5>
        </td>
        <td>
             <asp:Label id="lblOutput1" Font-Name="宋体" Font-Size="10.5pt" 
runat="server" />
        </td>
      </tr>
      <tr valign="top">
        <td>
            <h5><font face="行书">要检查的值:</font></h5>
            <asp:TextBox id="txtComp2" runat="server"/>
        </td>
        <td>
            <h5><font face="黑体">数据类型:日期最小值 (2002/1/1卡塔尔(قطر‎,最大值 
(2001/1/1)</font></h5>
        </td>
        <td>
             <asp:Label id="lblOutput2" Font-Name="宋体" Font-Size="10.5pt" 
runat="server" />
        </td>
      </tr>
      <tr valign="top">
        <td>
            <h5><font face="石籀文">要反省的值:</font></h5>
            <asp:TextBox id="txtComp3" runat="server"/>
        </td>
        <td>
            <h5><font face="甲骨文">数据类型:字符串最小值 (Aardvark卡塔尔,最大值 
(Zebra)</font></h5>
        </td>
        <td>
             <asp:Label id="lblOutput3" Font-Name="宋体" Font-Size="10.5pt" 
runat="server" />
        </td>
      </tr>
     </table>
     <asp:Button Text="验证" ID="Button1" onclick="Button1_Click" 
runat="server" />
     <asp:RangeValidator
        id="rangeValInteger"
        Type="Integer"
        ControlToValidate="txtComp1"
        MaximumValue="10"
        MinimumValue="1"
        runat="server"/>
     <asp:RangeValidator
        id="rangeValDate"
        Type="Date"
        ControlToValidate="txtComp2"
        MaximumValue="2001/1/1"
        MinimumValue="2000/1/1"
        runat="server"/>
     <asp:RangeValidator
        id="rangeValString"
        Type="String"
        ControlToValidate="txtComp3"
        MaximumValue="Zebra"
        MinimumValue="Aardvark"
        runat="server"/>
     <br>
     <asp:Label id="lblOutput" Font-Name="宋体" Font-Size="10.5pt" 
runat="server" />
    </form>
</body>
</html>

<ItemStyle VerticalAlign="Bottom">
</ItemStyle>

目录

<HeaderStyle HorizontalAlign="Center" VerticalAlign="Bottom" BackColor="#FF8000">
</HeaderStyle>

 

<FooterStyle HorizontalAlign="Justify" BackColor="White">
</FooterStyle>

  1. 注脚控件简要介绍

  2. 表达控件的施用情势

  3. 小结

<PagerStyle HorizontalAlign="Right" ForeColor="Red" Mode="NumericPages">
</PagerStyle>
      </asp:datagrid></td>
    </tr>
    <tr align="center">
     <td align=left><font size=2>一共</font> <asp:Label ID="lblallcount" Runat=server Font-size="8pt" ForeColor="#0000ff" font-names="verdana"></asp:Label> <font size=2>记录</font>
         <font size="2">共</font> <asp:label id="lblpagecount" runat="server" Font-Size="8pt" ForeColor="#0000ff" Font-Names="Verdana"></asp:label> <font size="2">页</font>
      <font size="2">第</font> <asp:label id="lblcurrentindex" runat="server" Font-Size="8pt" ForeColor="#0000ff" Font-Names="Verdana"></asp:label> <font size="2">页</font></td>
      <td align=right><asp:linkbutton id="first" runat="server" font-size="8pt" ForeColor="#3300ff" CommandArgument="first" Font-Names="Verdana"></asp:linkbutton>
      <asp:linkbutton id="prev" Font-Size="8pt" ForeColor="#3300ff" CommandArgument="prev" Runat="server" Font-Names="Verdana"></asp:linkbutton>
      <asp:linkbutton id="next" Font-Size="8pt" ForeColor="#3300ff" CommandArgument="next" Runat="server" Font-Names="Verdana"></asp:linkbutton>
      <asp:linkbutton id="last" Font-Size="8pt" ForeColor="#3300ff" CommandArgument="last" Runat="server" Font-Names="Verdana"></asp:linkbutton>
      <font size="2">跳转到第</font><asp:TextBox ID="to" Runat="server" Columns="1" /><font size="2">页</font><asp:Button ID="go" Text="GO" Runat="server" BackColor="WhiteSmoke" Font-Names="Verdana"/>
     </td>
    </tr>
   </table>
  </form>
</body>
</HTML>


2.webform1.cs

  1. 申明控件简要介绍

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

 

namespace page
{
/// <summary>
/// WebForm1 的摘要表明。
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
  protected System.Web.UI.WebControls.Label lblpagecount;
  protected System.Web.UI.WebControls.Label lblcurrentindex;
  protected System.Web.UI.WebControls.LinkButton first;
  protected System.Web.UI.WebControls.LinkButton prev;
  protected System.Web.UI.WebControls.LinkButton next;
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  protected System.Web.UI.WebControls.TextBox to;
  protected System.Web.UI.WebControls.Button go;
  protected System.Web.UI.WebControls.Label lblallcount;
  protected System.Web.UI.WebControls.LinkButton last;

从名称想到所包含的意义,验证控件就是校验客户输入数据科学的控件,如客商在文本框中输入数据后,便显得一条提示新闻,注脚了校验的数目是不合规的。验证进度不仅可以在服务器上实施,也足以在客商机上施行,在客商端运维的校验代码是数码交到以前被实行的,因而可以提升程序的属性。ASP.NET的印证控件能够举行二种校验,如数据范围检查、数据间的可比和自定义校验等等,上边包车型大巴内容将会挨个介绍那几个验证控件。

  void Page_Load(object sender, System.EventArgs e)
  {
   // 在这里间放置客户代码以初阶化页面
   first.Text="最首页";
   prev.Text="前一页";
   next.Text="下一页";
   last.Text="最后页";
   if(!IsPostBack)
   {
    BindGrid();
   }
  }

ASP.NET公有三种注解控件,分别如下: 

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必得的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
 
  /// <summary>
  /// 设计器帮助所需的主意 - 不要使用代码编辑器改正
  /// 此情势的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.Page_Changed);
   this.first.Click += new System.EventHandler(this.btnClick);
   this.prev.Click += new System.EventHandler(this.btnClick);
   this.next.Click += new System.EventHandler(this.btnClick);
   this.last.Click += new System.EventHandler(this.btnClick);
   this.go.Click += new System.EventHandler(this.goClick);
   this.Load += new System.EventHandler(this.Page_Load);

控件名 成效描叙

  }
  #endregion

RequiredFieldValidator(必需字段验证) 用于检查是还是不是有输入值

  void Page_Changed(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
  {
   DataGrid1.CurrentPageIndex=e.NewPageIndex;
   BindGrid();  
  }
  void BindGrid()
  {
   SqlConnection cn=new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=");
   cn.Open();
   SqlDataAdapter da=new SqlDataAdapter("select * from authors",cn);
   DataSet ds=new DataSet();
   da.Fill(ds,"authors");
   DataGrid1.DataSource=ds.Tables["authors"].DefaultView;
   DataGrid1.DataBind();
   cn.Close();
   showstate();
  }
  void showstate()
  {
   SqlConnection cn=new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=");
   cn.Open();
   SqlDataAdapter da=new SqlDataAdapter("select * from authors",cn);
   DataSet ds=new DataSet();
   da.Fill(ds,"authors");
   DataTable dt=ds.Tables["authors"];
   int count=dt.Rows.Count;
   lblallcount.Text=count.ToString();
   lblpagecount.Text=DataGrid1.PageCount.ToString();
   lblcurrentindex.Text=(DataGrid1.CurrentPageIndex+1).ToString();
  }
  void btnClick(object sender,System.EventArgs e)
  {
   string arg=((LinkButton)sender).CommandArgument;
   switch(arg)
   {
    case ("first"):
     DataGrid1.CurrentPageIndex=0;
     break;
    case ("prev"):
     if(DataGrid1.CurrentPageIndex>0)
      DataGrid1.CurrentPageIndex--;
     break;
    case ("next"):
     if(DataGrid1.CurrentPageIndex<(DataGrid1.PageCount-1))
      DataGrid1.CurrentPageIndex++;
     break;
    case ("last"):
     DataGrid1.CurrentPageIndex=DataGrid1.PageCount-1;
     break;
    default:
     DataGrid1.CurrentPageIndex=Convert.ToInt32(arg);
     break;
   }
   BindGrid();
  }

CompareValidator(相比较印证) 按设定比非常多少个输入

  private void goClick(object sender, System.EventArgs e)
  {
   if(to.Text.Trim()!="")
   {
    int index=Int32.Parse(to.Text.Trim())-1;
    if(index>=0&&index<DataGrid1.PageCount)
    {
     DataGrid1.CurrentPageIndex=index;
    }
   }
   BindGrid();
  }

RangeValidator(范围验证) 输入是不是在钦定范围

}
}

RegularExpressionValidator(正则表明式验证) 正则表明式验证控件

好了,今后以此分页的web 程序完毕了,你去试试.

CustomValidator(自定义表明) 自定义表明控件

ValidationSummary(验证总计) 总括验证结果


  1. 证明控件的接受办法

 

① RequiredFieldValidator控件

当页面上的控件须要必得输入数据时,Required菲尔德Validator就起效果了,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控件能够判断顾客输入的说明式是不是正确,如电话号码、邮政编码、U凯雷德L等,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>

  1. 小结

 

上述内容仅是ASP.NET验证控件的精练介绍,使用这么些控件熟识后便得以裁减开拓时间,更能够省去多量的编辑JavaScript的事业。

Page.IsValid

在ASP.Net中,为了方便表单的求证,提供了认证控件来实现表单输入数据的认证。难题的源点是对于asp:Button控 件,点击的时候是私下认可先实行表单的证实的。

一些朋友期望在表单里有多个按键,在那之中有的开关试行的操作和表单自身毫不相关,无需申明,但也暗中认可必得开展表明,对 程序设计上导致好多烦心。

解决措施:在急需表明的时候,能够手工业调用验证代码:验证控件.Validate(State of Qatar可能Page.Validate(State of Qatar实行表明。

*****************************************

朝气蓬勃体化的印证措施

//default.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"";

<html xmlns=";
<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.IsValidState of Qatar //当全部页直面象验证通过后, 将设置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(hcState of Qatar; //保存到cookie中去, 不过未有页面前遇到象, 所以须求通过context

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

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

publicbool IsReusable {
get {
returnfalse;
}
}

}

本文由10bet手机官网发布于多线程,转载请注明出处:验证控件,net轻松打造功能完备的分页技术10bet手机官网:

上一篇:没有了 下一篇:无组件图片与文本同步存入数据库的最简单的办法,asp无组件上传的原理
猜你喜欢
热门排行
精彩图文