<%@ Page clienttarget=downlevel %>
 
<html>
<title>第十六例 CompareValidator和CustomValidator控件使用</title>
<head>
   <script language="C#" runat="server">
 
      void Button_Click(Object sender, EventArgs e) 
      {

         Random rand_number = new Random();
//生成一个0-10随机数  
         Compare1.ValueToCompare = rand_number.Next(1, 10).ToString();
//开始进行比较
         Compare1.Validate(); 
         if (Page.IsValid) 
         {
            lblOutput.Text = "恭喜您，您猜的数字和随机生成的一样<BR>";
         }
         else 
         {
            lblOutput.Text = "<BR><BR>对不起，您猜错了";
         }
//在页面上显示随机生成的数字
         lblOutput.Text += "<br><br>" + "随机生成的数字是: <font color=red size=4>" + Compare1.ValueToCompare+"<BR></font>";

      }

//自定义验证函数
      void ServerValidation (object source, ServerValidateEventArgs args)
      {
         try 
         {
//取得文本框的数字，验证是否在1-10之间
            int i = int.Parse(args.Value);
            args.IsValid = ((i < 10) && (i > 0 ));

         }

         catch
         {
            args.IsValid = false;
         }
      }

 
   </script>
 
</head>
<body>
 
   <form runat=server>

      <h3><font face="Verdana">第十六例 CompareValidator和CustomValidator控件使用</font></h3>

      <h5><font face="Verdana">请您输入一个1-10的随机数字:</font></h5>    
     
      <asp:TextBox id="TextBox1" 
           runat="server"/>

      <asp:CompareValidator id="Compare1" 
           ControlToValidate="TextBox1"
           ValueToCompare="0"  
           Type="Integer" 
           ErrorMessage="猜测错误!!"
           Text="*"
           Display="Dynamic"
           runat="server"/>

      <br><br>

      <asp:Button id="Button1"
           Text="验证"
           OnClick="Button_Click"
           runat="server"/>
 
      <br><br>    
      &nbsp;&nbsp;

      <asp:CustomValidator id="CustomValidator1"
           ControlToValidate="Textbox1"
           ClientValidationFunction="ClientValidate"
           OnServerValidate="ServerValidation"
           Display="Static"
           ErrorMessage="输入数据没有在1-10之间!"
           ForeColor="green"
           BackColor="Red"
           Font-Name="verdana" 
           Font-Size="10pt"
           runat="server"/>
	<BR>
       
      <asp:Label id="lblOutput" 
           Font-Name="verdana" 
           Font-Size="10pt" 
           runat="server"/>

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