Page.Validate Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Instrui quaisquer controlos de validação incluídos na página a validarem a informação atribuída.
Sobrecargas
| Name | Description |
|---|---|
| Validate() |
Instrui quaisquer controlos de validação incluídos na página a validarem a informação atribuída. |
| Validate(String) |
Instrui os controlos de validação no grupo de validação especificado a validarem a informação atribuída. |
Validate()
Instrui quaisquer controlos de validação incluídos na página a validarem a informação atribuída.
public:
virtual void Validate();
public virtual void Validate();
abstract member Validate : unit -> unit
override this.Validate : unit -> unit
Public Overridable Sub Validate ()
Exemplos
O seguinte exemplo de código chama o Validate método numa página num cenário com vários grupos de validação diferentes definidos.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<%@ 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>
Observações
Este método é invocado quando um utilizador clica em qualquer controlo ASP.NET servidor que tenha a propriedade CausesValidation definida para true, que é o padrão. Estes incluem os Buttoncontrolos do servidor web , ImageButtonLinkButton , HtmlInputImageHtmlInputButton, e HtmlButton os controlos do servidor HTML, e controlos que podem ser automaticamente publicados de volta ao servidor, como os TextBoxcontrolos , CheckBox, ListControl, e BulletedList .
Para desativar a validação de qualquer controlo de botão na página, defina a propriedade do CausesValidation controlo de botão para false.
Quando este método é invocado, ele itera através dos controlos de validação contidos no ValidatorCollection objeto associado à Page.Validators propriedade e invoca a lógica de validação para cada controlo de validação no grupo de validação atual. O grupo de validação é determinado pelo controlo que publicou a página no servidor. Se não for especificado nenhum grupo de validação, então não é utilizado nenhum grupo de validação.
Note
O comportamento da validação de páginas mudou. Na ASP.NET 2.0, os controlos já não chamam o método Page.Validate(); utilizam o método Page.Validate(String) em vez disso. Se usar o método Page.Validate() numa página ASP.NET 2.0, os grupos de validação são ignorados e todos os controlos são validados.
Notas para Herdeiros
O método Validate() não é utilizado pela ASP.NET 2.0. Quando estiver a usar ASP.NET 2.0, sobrescrita o método Validate(String) para alterar o comportamento de validação da página.
Ver também
Aplica-se a
Validate(String)
Instrui os controlos de validação no grupo de validação especificado a validarem a informação atribuída.
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 controlos a validar.
Exemplos
O seguinte exemplo de código chama o Validate método numa página num cenário com vários grupos de validação diferentes definidos.
Importante
Este exemplo tem uma caixa de texto que aceita a entrada do utilizador, o que constitui uma potencial ameaça à segurança. Por defeito, as páginas Web do ASP.NET validam que a entrada do utilizador não inclui elementos de script ou HTML. Para mais informações, consulte Visão Geral dos Exploits de Scripts.
<%@ 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>
Observações
Este método é invocado quando um utilizador clica em qualquer controlo ASP.NET servidor que tenha a propriedade CausesValidation definida para true, que é o padrão. Estes incluem os Buttoncontrolos do servidor web , ImageButtonLinkButton , HtmlInputImageHtmlInputButton, e HtmlButton os controlos do servidor HTML, e controlos que podem ser automaticamente publicados de volta ao servidor, como os TextBoxcontrolos , CheckBox, ListControl, e BulletedList .
Para desativar a validação de qualquer controlo de botão na página, defina a propriedade do CausesValidation controlo de botão para false.
O Validate método valida o grupo de validação especificado. Após chamar o Validate método num grupo de validação, o IsValid método só retornará true se tanto o grupo de validação especificado como o grupo de validação do controlo que causou a publicação da página no servidor forem válidos.