ASP.Net/Validation by Control/ValidationSummary

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Change invalid control background color (VB.net)

<%@ Page Language="VB" %>
<script runat="server">
    Sub Page_PreRender()
        For Each valControl As BaseValidator In Page.Validators
            Dim assControl As WebControl = Page.FindControl(valControl.ControlToValidate)
            If Not valControl.IsValid Then
                assControl.BackColor = Drawing.Color.Yellow
            Else
                assControl.BackColor = Drawing.Color.White
            End If
        Next
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Validators</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
    <asp:Label
        id="lblFirstName"
        Text="First Name"
        AssociatedControlID="txtFirstName"
        Runat="server" />
    <br />    
    <asp:TextBox
        id="txtFirstName"
        Runat="server" />
    <asp:RequiredFieldValidator
        id="reqFirstName"
        ControlToValidate="txtFirstName"
        Text="(Required)"
        EnableClientScript="false"
        Runat="server" />   
     
    <br /><br />
        
    <asp:Label
        id="lblLastName"
        Text="Last Name"
        AssociatedControlID="txtLastName"
        Runat="server" />
    <br />    
    <asp:TextBox
        id="txtLastname"
        Runat="server" />
    <asp:RequiredFieldValidator
        id="reqLastName"
        ControlToValidate="txtLastName"
        Text="(Required)" 
        EnableClientScript="false"
        Runat="server" />   
     
     <br /><br />
     
     <asp:Button
        id="btnSubmit"
        Text="Submit"
        Runat="server" />   
    </div>
    </form>
</body>
</html>



Creating a Basic ValidationSummary Control (VB.net)

<%@ Page Language=VB Debug=true %>
<HTML>
<HEAD>
<TITLE>Creating a Basic ValidationSummary Control</TITLE>
</HEAD>
<form runat="server">
<BR>
<asp:validationsummary 
    id="vsAllErrors" 
    showsummary="True"
    runat="server"
    headertext="For these reasons, your data could not be processed:"
    displaymode="list"
    font-name="Comic Sans MS" 
    font-size="12"
/>
<BR>
Enter Your Name:<BR>
<asp:textbox 
    id="txtName" 
    runat=server 
/>
<asp:requiredfieldvalidator 
    id="rfvName"
    controltovalidate="txtName"
    errormessage="The name field is required!"
    runat=server
>
*
</asp:requiredfieldvalidator>
<BR>
Please enter a Date:<BR>
<asp:textbox 
    id="txtDate" 
    runat=server 
/>
<asp:comparevalidator 
    id="cvCheckDate" 
    controltovalidate="txtDate" 
    operator="DataTypeCheck" 
    type="Date" 
    errormessage="The date field must be a date!"
    runat="server"
>
*
</asp:CompareValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    type="Submit"
    runat="server"
/>
</form>
</BODY>
</HTML>



Detail summary reason (VB.net)

<%@ Page Language=VB Debug=true %>
<HTML>
<HEAD>
<TITLE>Creating a Basic ValidationSummary Control</TITLE>
</HEAD>
<BODY LEFTMARGIN="40">
<form runat="server">
<BR>
<asp:validationsummary 
    id="vsAllErrors" 
    showsummary="True"
    runat="server"
    headertext="For these reasons, your data could not be processed:"
    displaymode="bulletlist"
    font-name="Comic Sans MS" 
    font-size="12"
/>
<BR>
Enter Your Name:<BR>
<asp:textbox 
    id="txtName" 
    runat=server 
/>
<asp:requiredfieldvalidator 
    id="rfvName"
    controltovalidate="txtName"
    errormessage="The name field is required!"
    runat=server
>
*
</asp:requiredfieldvalidator>
<BR>
Please enter a Date:<BR>
<asp:textbox 
    id="txtDate" 
    runat=server 
/>
<asp:comparevalidator 
    id="cvCheckDate" 
    controltovalidate="txtDate" 
    operator="DataTypeCheck" 
    type="Date" 
    errormessage="The date field must be a date!"
    runat="server"
>
*
</asp:CompareValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    type="Submit"
    runat="server"
/>
</form>
</BODY>
</HTML>



Displaying Error Messages in a Message Box Using the ValidationSummary Control (VB.net)

<%@ Page Language=VB Debug=true %>
<HTML>
<HEAD>
<TITLE>Displaying Error Messages in a Message Box Using the ValidationSummary Control</TITLE>
</HEAD>
<BODY LEFTMARGIN="40">
<form runat="server">
<BR>
<asp:validationsummary 
    id="vsAllErrors" 
    showsummary="False"
    showmessagebox="True"
    runat="server"
    headertext="For these reasons, your data could not be processed:"
/>
<BR>
Enter Your Name:<BR>
<asp:textbox 
    id="txtName" 
    runat=server 
/>
<asp:requiredfieldvalidator 
    id="rfvName"
    controltovalidate="txtName"
    errormessage="The name field is required!"
    runat=server
>
*
</asp:requiredfieldvalidator>
<BR>
Please enter a Date:<BR>
<asp:textbox 
    id="txtDate" 
    runat=server 
/>
<asp:comparevalidator 
    id="cvCheckDate" 
    controltovalidate="txtDate" 
    operator="DataTypeCheck" 
    type="Date" 
    errormessage="The date field must be a date!"
    runat="server"
>
*
</asp:CompareValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    type="Submit"
    runat="server"
/>
</form>
</BODY>
</HTML>



ValidationSummary Demo (VB.net)

<%@ Page Language=VB Debug=true %>
<%@ Import Namespace="System.Data" %>
<script runat=server>
</SCRIPT>
<HTML>
<HEAD>
<TITLE>ValidationSummary Control Sample Page</TITLE>
</HEAD>
<BODY  >
<form runat="server">
<Font Face="Tahoma">
<asp:ValidationSummary 
    ID="vsAllErros" 
    DisplayMode="BulletList" 
    ShowMessageBox="False"
    ShowSummary="True"
    runat="server"
    HeaderText="For these reasons, your data could not be processed:"
    Font-Name="Comic Sans MS" 
    Font-Size="12"
/>
<BR>
<asp:Label
    id="lblMessage"
    runat="server"
    Font-Bold="True"
    Text="Date"
/>
<asp:TextBox 
    id="txtDateField" 
    Columns="25"
    MaxLength="30"
    runat=server 
/>
<asp:CompareValidator 
    id="cvDateField" 
    ControlToValidate="txtDateField" 
    Operator="DataTypeCheck" 
    Type="Date" 
    ErrorMessage="You must enter a date!"
    Display="Dynamic"
    Font-Size="10pt"
    runat="server">
    *
</asp:CompareValidator>
<BR><BR>
<asp:Label
    id="lblMessage2"
    runat="server"
    Font-Bold="True"
    Text="Number"
/>
<asp:TextBox 
    id="txtNumber" 
    Columns="25"
    MaxLength="30"
    runat=server 
/>
<asp:CompareValidator 
    id="cvNumber" 
    ControlToValidate="txtNumber" 
    Operator="DataTypeCheck" 
    Type="Integer" 
    ErrorMessage="You must enter a whole number!"
    Display="Dynamic"
    runat="server">
    *
</asp:CompareValidator>
<BR><BR>
<asp:Label
    id="lblMessage3"
    runat="server"
    Font-Bold="True"
    Text="Make the same"
/>
<asp:TextBox 
    id="txtSame1" 
    Columns="25"
    MaxLength="30"
    runat=server 
/>
<asp:TextBox 
    id="txtSame2" 
    Columns="25"
    MaxLength="30"
    runat=server 
/>
<asp:CompareValidator id="cvSame"
    ControlToValidate="txtSame1" 
    ControlToCompare="txtSame2"
    ErrorMessage="Fields don"t match!"
    Display="Dynamic"
    Font-Name="Tahoma"
    Font-Size="10pt"
    runat=server>
    *
</asp:CompareValidator>
<BR><BR>
<asp:button 
    id="butOK"
    text="OK"
    Type="Submit"
    runat="server"
/>
</Font>
</Form>
</BODY>
</HTML>



Validation summary in action (VB.net)

<%@ Page Language="vb" %>
<html>
<head>
   <title>Validation Control Example</title>
    <script language="javascript">
    <!--
      function ClientValidate(source, arguments)
      {
         //alert(arguments.Value);
         var r, re;      //Declare variables.
         re = new RegExp(/^[1-9][0-9][0-9][0-9]$/);  //Create regular expression object.
         r = re.test(arguments.Value);  //Test for match.
         arguments.IsValid = r;    //Return results.
      }
   -->
   </script>
   <script runat="server">
      Sub Page_Load()
         vsSummary.DisplayMode = ValidationSummaryDisplayMode.List
      End Sub
      Sub ServerValidation (source As object, args As ServerValidateEventArgs)
         Dim RegExVal As New System.Text.RegularExpressions.Regex("^\d{4}$")
         If RegExVal.IsMatch(args.Value) Then
            args.IsValid = True
         Else
            args.IsValid = False
         End If
      End Sub
   </script>
</head>
<body>
   <h1>Validation Control Example</h1>
   <form runat="server">
      <asp:table id="MyTable" border="1" cellpadding="5" cellspacing="0" runat="server">
         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               Compare Validator Control:
               <br><br>
               Enter two numbers to compare
            </asp:tablecell>
            <asp:tablecell runat="server">
               <asp:textbox id="value1" runat="server"/><br>
               <asp:textbox id="value2" runat="server"/><br>
               <asp:comparevalidator id="cvCompare" 
                  controltovalidate="value1" 
                  controltocompare="value2" 
                  operator="equal" 
                  type="integer" 
                  errormessage="Fields are not equal!" 
                  display="dynamic" 
                  runat="server"/>
            </asp:tablecell>
         </asp:tablerow>

         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               ValidationSummary Control:
            </asp:tablecell>
            <asp:tablecell runat="server">
               <asp:validationsummary id="vsSummary"
                  displaymode="bulletlist" 
                  headertext="Page has the following errors: "
                  showsummary="true" 
                  showmessagebox="false"
                  runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
         <asp:tablerow runat="server">
            <asp:tablecell colspan="2" runat="server">
               <asp:button text="submit" runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
      </asp:table>
      <asp:label id="MyLabel" runat="server"/>
   </form>
</body>
</html>



Validation summary in code behind (C#)

<%@ Page language="c#" src="ValidationSummary.aspx.cs" AutoEventWireup="false" Inherits="MyOwnValidationSummary" %>
<HTML>
  <body>
    <form id="Form1" method="post" runat="server">
      <P>A number (1 to 10):
        <asp:textbox id="txtValidated" runat="server"></asp:textbox>&nbsp;
        <asp:rangevalidator id="RangeValidator" runat="server" Display="None" Type="Integer" MinimumValue="1" MaximumValue="10" ControlToValidate="txtValidated" ErrorMessage="The First Number Is Not In The Range"></asp:rangevalidator><BR>
        <BR>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Not validated:&nbsp;
        <asp:textbox id="txtNotValidated" runat="server"></asp:textbox><BR>
      </P>
      <P><BR>
        <asp:button id="cmdOK" runat="server" Text="OK"></asp:button><BR>
        <BR>
        <asp:label id="lblMessage" runat="server" EnableViewState="False"></asp:label><BR>
        <BR>
        <asp:ValidationSummary id="ValidationSummary1" runat="server" ShowMessageBox="True"></asp:ValidationSummary></P>
    </form>
  </body>
</HTML>

<%--
using System;
using System.Collections;
using System.ruponentModel;
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;
  public class MyOwnValidationSummary : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.TextBox txtValidated;
    protected System.Web.UI.WebControls.RangeValidator RangeValidator;
    protected System.Web.UI.WebControls.TextBox txtNotValidated;
    protected System.Web.UI.WebControls.Button cmdOK;
    protected System.Web.UI.WebControls.Label lblMessage;
    protected System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
  
    private void Page_Load(object sender, System.EventArgs e)
    {
      // Put user code to initialize the page here
    }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
      this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
    private void cmdOK_Click(object sender, System.EventArgs e)
    {
      if (!this.IsValid) return;
      lblMessage.Text = "cmdOK_Click event handler executed.";
    }
  }

--%>