Page.Validate Método

Definição

Instrui os controles de validação incluídos na página a validar suas informações atribuídas.

Sobrecargas

Validate()

Instrui os controles de validação incluídos na página a validar suas informações atribuídas.

Validate(String)

Instrui os controles de validação no grupo de validação especificado para validar suas informações atribuídas.

Validate()

Instrui os controles de validação incluídos na página a validar suas informações atribuídas.

public:
 virtual void Validate();
public virtual void Validate ();
abstract member Validate : unit -> unit
override this.Validate : unit -> unit
Public Overridable Sub Validate ()

Exemplos

O exemplo de código a seguir chama o Validate método em uma página em um cenário com vários grupos de validação diferentes definidos.

Importante

Este exemplo tem uma caixa de texto que aceita a entrada do usuário, que é uma ameaça à segurança em potencial. Por padrão, ASP.NET páginas da Web validam que a entrada do usuário não inclui elementos HTML ou script. Para obter mais informações, consulte Visão geral de explorações de script.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void Button_Click(object sender, EventArgs e)
  {
    switch (((Button)sender).ID)
    {
      case "Button1":
        if (TextBoxValidator1.IsValid)
        {
          Label1.Text = "TextBox validates.";
        }
        else
        {
          Label1.Text = "";
          Label4.Text = "";
        }
        break;
      case "Button2":
        // Must explicitly cause Validate here because 
        // Button2 has CausesValidation set to false.
        Validate("Group2");
        if (CustomValidator.IsValid)
        {
          Label2.Text = "CheckBox validates.";
        }
        else
        {
          Label2.Text = "";
          Label4.Text = "";
        }
        break;
      default:
      Label1.Text = "";
      Label2.Text = "";
      break;
        
    }
  }

  // Custom validator for check box.
  protected void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
  {
    args.IsValid = (CheckBox1.Checked == true);
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (IsPostBack && Context.Request.Form["__EVENTTARGET"] == "TextBox2")
    {
      // Handle AutoPostBack TextBox.
      Validate("Group3");
      if (Page.IsValid)
      {
        Label3.Text = "AutoPostBack TextBox validates.";
      }
      else
      {
        Label3.Text = "";
        Label4.Text = "";
      }
    }
    
  }

  protected void Button3_Click(object sender, EventArgs e)
  {
    Validate();
    if (Page.IsValid)
      Label4.Text = "All controls valid.";
    else
    {
      Label1.Text = "";
      Label2.Text = "";
      Label3.Text = "";
      Label4.Text = "";
    }

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Page Validate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      TextBox
      <asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator Display="Static" ID="TextBoxValidator1" ValidationGroup="Group1" runat="server" ControlToValidate="TextBox1" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <br />
      CheckBox
      <asp:CheckBox ID="CheckBox1" ValidationGroup="Group2" runat="server" />
      <asp:CustomValidator ID="CustomValidator" ValidationGroup="Group2" runat="server" Text="(this option required)" OnServerValidate="CustomValidator_ServerValidate" EnableClientScript="False"></asp:CustomValidator>
      <br />
      <asp:Button ID="Button1" ValidationGroup="Group1" CausesValidation="true" runat="server" Text="Validate Group1 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label1" runat="server"></asp:Label>
      <br />
      <asp:Button ID="Button2" ValidationGroup="Group2" CausesValidation="false" runat="server" Text="Validate Group2 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label2" runat="server"></asp:Label>
      <br />
      <br />
      AutoPostBack TextBox
      <asp:TextBox AutoPostBack="true" ID="TextBox2" ValidationGroup="Group3" runat="server" CausesValidation="true"></asp:TextBox>
      <asp:RequiredFieldValidator ID="TextBoxValidator2" ValidationGroup="Group3" runat="server" ControlToValidate="TextBox2" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <asp:Label ID="Label3" runat="server"></asp:Label>
      <br />
      <br />
      <asp:Button ID="Button3" CausesValidation="true" runat="server" Text="Validate All Controls" OnClick="Button3_Click" />
      <asp:Label ID="Label4" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Select Case CType(sender, Button).ID
      Case "Button1"
        If TextBoxValidator1.IsValid Then
          Label1.Text = "TextBox validates."
        Else
          Label1.Text = ""
          Label4.Text = ""
        End If
      Case "Button2"
        ' Must explicitly cause Validate here because 
        ' Button2 has CausesValidation set to false.
        Validate("Group2")
        If CustomValidator.IsValid Then
          Label2.Text = "CheckBox validates."
        Else
          Label2.Text = ""
          Label4.Text = ""
        End If
      Case Else
        Label1.Text = ""
        Label2.Text = ""
    End Select

  End Sub
  
  Protected Sub CustomValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
     
    args.IsValid = (CheckBox1.Checked)

  End Sub
  
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    If (IsPostBack) Then
      
    ' Handle AutoPostBack TextBox.
      Validate("Group3")
      If (Page.IsValid) Then
        Label3.Text = "AutoPostBack TextBox validates."
      Else
        Label3.Text = ""
        Label4.Text = ""
      End If
    End If
    
  End Sub

  Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
  
    Validate()
    If (Page.IsValid) Then
      Label4.Text = "All controls valid."
    Else
      Label1.Text = ""
      Label2.Text = ""
      Label3.Text = ""
      Label4.Text = ""
    End If
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Page Validate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      TextBox
      <asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator Display="Static" ID="TextBoxValidator1" ValidationGroup="Group1" runat="server" ControlToValidate="TextBox1" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <br />
      CheckBox
      <asp:CheckBox ID="CheckBox1" ValidationGroup="Group2" runat="server" />
      <asp:CustomValidator ID="CustomValidator" ValidationGroup="Group2" runat="server" Text="(this option required)" OnServerValidate="CustomValidator_ServerValidate" EnableClientScript="False"></asp:CustomValidator>
      <br />
      <asp:Button ID="Button1" ValidationGroup="Group1" CausesValidation="true" runat="server" Text="Validate Group1 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label1" runat="server"></asp:Label>
      <br />
      <asp:Button ID="Button2" ValidationGroup="Group2" CausesValidation="false" runat="server" Text="Validate Group2 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label2" runat="server"></asp:Label>
      <br />
      <br />
      AutoPostBack TextBox
      <asp:TextBox AutoPostBack="true" ID="TextBox2" ValidationGroup="Group3" runat="server" CausesValidation="true"></asp:TextBox>
      <asp:RequiredFieldValidator ID="TextBoxValidator2" ValidationGroup="Group3" runat="server" ControlToValidate="TextBox2" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <asp:Label ID="Label3" runat="server"></asp:Label>
      <br />
      <br />
      <asp:Button ID="Button3" CausesValidation="true" runat="server" Text="Validate All Controls" OnClick="Button3_Click" />
      <asp:Label ID="Label4" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>

Comentários

Esse método é invocado quando um usuário clica em qualquer controle de servidor ASP.NET que tenha a CausesValidation propriedade definida como true, que é o padrão. Estes incluem os Buttoncontroles HtmlInputImageHtmlInputButtonde LinkButton ImageButtonservidor Web, os controles de servidor HTML e HtmlButton , e controles que podem ser postados automaticamente no servidor, como o TextBox, ListControlCheckBoxe BulletedList controles.

Para desabilitar a validação de qualquer controle de botão na página, defina a propriedade do controle de CausesValidation botão como false.

Quando esse método é invocado, ele itera por meio dos controles de validação contidos no ValidatorCollection objeto associado Page.Validators à propriedade e invoca a lógica de validação para cada controle de validação no grupo de validação atual. O grupo de validação é determinado pelo controle que postou a página no servidor. Se nenhum grupo de validação for especificado, nenhum grupo de validação será usado.

Observação

O comportamento da validação de página foi alterado. Em ASP.NET 2.0, os controles não chamam mais o Page.Validate() método; eles usam o Page.Validate(String) método em vez disso. Se você usar o Page.Validate() método em uma página ASP.NET 2.0, os grupos de validação serão ignorados e todos os controles serão validados.

Notas aos Herdeiros

O Validate() método não é usado pelo ASP.NET 2.0. Quando você estiver usando ASP.NET 2.0, substitua o método para alterar o Validate(String) comportamento de validação de página.

Confira também

Aplica-se a

Validate(String)

Instrui os controles de validação no grupo de validação especificado para validar suas informações atribuídas.

public:
 virtual void Validate(System::String ^ validationGroup);
public virtual void Validate (string validationGroup);
abstract member Validate : string -> unit
override this.Validate : string -> unit
Public Overridable Sub Validate (validationGroup As String)

Parâmetros

validationGroup
String

O nome do grupo de validação dos controles para validar.

Exemplos

O exemplo de código a seguir chama o Validate método em uma página em um cenário com vários grupos de validação diferentes definidos.

Importante

Este exemplo tem uma caixa de texto que aceita a entrada do usuário, que é uma ameaça à segurança em potencial. Por padrão, ASP.NET páginas da Web validam que a entrada do usuário não inclui elementos HTML ou script. Para obter mais informações, consulte Visão geral de explorações de script.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void Button_Click(object sender, EventArgs e)
  {
    switch (((Button)sender).ID)
    {
      case "Button1":
        if (TextBoxValidator1.IsValid)
        {
          Label1.Text = "TextBox validates.";
        }
        else
        {
          Label1.Text = "";
          Label4.Text = "";
        }
        break;
      case "Button2":
        // Must explicitly cause Validate here because 
        // Button2 has CausesValidation set to false.
        Validate("Group2");
        if (CustomValidator.IsValid)
        {
          Label2.Text = "CheckBox validates.";
        }
        else
        {
          Label2.Text = "";
          Label4.Text = "";
        }
        break;
      default:
      Label1.Text = "";
      Label2.Text = "";
      break;
        
    }
  }

  // Custom validator for check box.
  protected void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
  {
    args.IsValid = (CheckBox1.Checked == true);
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (IsPostBack && Context.Request.Form["__EVENTTARGET"] == "TextBox2")
    {
      // Handle AutoPostBack TextBox.
      Validate("Group3");
      if (Page.IsValid)
      {
        Label3.Text = "AutoPostBack TextBox validates.";
      }
      else
      {
        Label3.Text = "";
        Label4.Text = "";
      }
    }
    
  }

  protected void Button3_Click(object sender, EventArgs e)
  {
    Validate();
    if (Page.IsValid)
      Label4.Text = "All controls valid.";
    else
    {
      Label1.Text = "";
      Label2.Text = "";
      Label3.Text = "";
      Label4.Text = "";
    }

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Page Validate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      TextBox
      <asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator Display="Static" ID="TextBoxValidator1" ValidationGroup="Group1" runat="server" ControlToValidate="TextBox1" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <br />
      CheckBox
      <asp:CheckBox ID="CheckBox1" ValidationGroup="Group2" runat="server" />
      <asp:CustomValidator ID="CustomValidator" ValidationGroup="Group2" runat="server" Text="(this option required)" OnServerValidate="CustomValidator_ServerValidate" EnableClientScript="False"></asp:CustomValidator>
      <br />
      <asp:Button ID="Button1" ValidationGroup="Group1" CausesValidation="true" runat="server" Text="Validate Group1 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label1" runat="server"></asp:Label>
      <br />
      <asp:Button ID="Button2" ValidationGroup="Group2" CausesValidation="false" runat="server" Text="Validate Group2 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label2" runat="server"></asp:Label>
      <br />
      <br />
      AutoPostBack TextBox
      <asp:TextBox AutoPostBack="true" ID="TextBox2" ValidationGroup="Group3" runat="server" CausesValidation="true"></asp:TextBox>
      <asp:RequiredFieldValidator ID="TextBoxValidator2" ValidationGroup="Group3" runat="server" ControlToValidate="TextBox2" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <asp:Label ID="Label3" runat="server"></asp:Label>
      <br />
      <br />
      <asp:Button ID="Button3" CausesValidation="true" runat="server" Text="Validate All Controls" OnClick="Button3_Click" />
      <asp:Label ID="Label4" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Select Case CType(sender, Button).ID
      Case "Button1"
        If TextBoxValidator1.IsValid Then
          Label1.Text = "TextBox validates."
        Else
          Label1.Text = ""
          Label4.Text = ""
        End If
      Case "Button2"
        ' Must explicitly cause Validate here because 
        ' Button2 has CausesValidation set to false.
        Validate("Group2")
        If CustomValidator.IsValid Then
          Label2.Text = "CheckBox validates."
        Else
          Label2.Text = ""
          Label4.Text = ""
        End If
      Case Else
        Label1.Text = ""
        Label2.Text = ""
    End Select

  End Sub
  
  Protected Sub CustomValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
     
    args.IsValid = (CheckBox1.Checked)

  End Sub
  
  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    If (IsPostBack) Then
      
    ' Handle AutoPostBack TextBox.
      Validate("Group3")
      If (Page.IsValid) Then
        Label3.Text = "AutoPostBack TextBox validates."
      Else
        Label3.Text = ""
        Label4.Text = ""
      End If
    End If
    
  End Sub

  Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
  
    Validate()
    If (Page.IsValid) Then
      Label4.Text = "All controls valid."
    Else
      Label1.Text = ""
      Label2.Text = ""
      Label3.Text = ""
      Label4.Text = ""
    End If
    
  End Sub
  
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Page Validate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      TextBox
      <asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server"></asp:TextBox>
      <asp:RequiredFieldValidator Display="Static" ID="TextBoxValidator1" ValidationGroup="Group1" runat="server" ControlToValidate="TextBox1" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <br />
      CheckBox
      <asp:CheckBox ID="CheckBox1" ValidationGroup="Group2" runat="server" />
      <asp:CustomValidator ID="CustomValidator" ValidationGroup="Group2" runat="server" Text="(this option required)" OnServerValidate="CustomValidator_ServerValidate" EnableClientScript="False"></asp:CustomValidator>
      <br />
      <asp:Button ID="Button1" ValidationGroup="Group1" CausesValidation="true" runat="server" Text="Validate Group1 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label1" runat="server"></asp:Label>
      <br />
      <asp:Button ID="Button2" ValidationGroup="Group2" CausesValidation="false" runat="server" Text="Validate Group2 Controls" OnClick="Button_Click" />
      <asp:Label ID="Label2" runat="server"></asp:Label>
      <br />
      <br />
      AutoPostBack TextBox
      <asp:TextBox AutoPostBack="true" ID="TextBox2" ValidationGroup="Group3" runat="server" CausesValidation="true"></asp:TextBox>
      <asp:RequiredFieldValidator ID="TextBoxValidator2" ValidationGroup="Group3" runat="server" ControlToValidate="TextBox2" ErrorMessage="(please enter some text)" EnableClientScript="False"></asp:RequiredFieldValidator>
      <asp:Label ID="Label3" runat="server"></asp:Label>
      <br />
      <br />
      <asp:Button ID="Button3" CausesValidation="true" runat="server" Text="Validate All Controls" OnClick="Button3_Click" />
      <asp:Label ID="Label4" runat="server"></asp:Label>
    
    </div>
    </form>
</body>
</html>

Comentários

Esse método é invocado quando um usuário clica em qualquer controle de servidor ASP.NET que tenha a CausesValidation propriedade definida como true, que é o padrão. Estes incluem os Buttoncontroles HtmlInputImageHtmlInputButtonde LinkButton ImageButtonservidor Web, os controles de servidor HTML e HtmlButton , e controles que podem ser postados automaticamente no servidor, como o TextBox, ListControlCheckBoxe BulletedList controles.

Para desabilitar a validação de qualquer controle de botão na página, defina a propriedade do controle de CausesValidation botão como false.

O Validate método valida o grupo de validação especificado. Depois de chamar o Validate método em um grupo de validação, o IsValid método retornará true somente se o grupo de validação especificado e o grupo de validação do controle que fez com que a página fosse postada no servidor forem válidas.

Confira também

Aplica-se a