After validating we may thing that we have built a secure application but a hacker could disable JavaScript and bypass all our validators ! This is where the Page.Validate() method and more importantly, the Page.IsValid property come in.
The Page.Validate() method is fired automatically by controls that have the CausesValidation property set to true. Note that the Button control’s CausesValidation property is true by default.
We should check this property only after calling the Page. Validate () method, or set the CausesValidation property to true which is by default true for button control.
Implementation: Let’s check by an example
- Place two TextBox control for username and Password, a Button control for Login button and two RequiredFieldValidator for validating username and password whether username and password entered or not.
<table>
<tr>
<td>
User Name</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvUserName" runat="server"
ControlToValidate="txtUserName" ErrorMessage="Please enter username"
ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPwd" runat="server"
ControlToValidate="txtPwd" ErrorMessage="Please enter password"
ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnLogin" runat="server" Text="Login"
onclick="btnLogin_Click" />
</td>
</tr>
</table>
C#.NET Code
protected void btnLogin_Click(object sender, EventArgs e)
{
Page.Validate(); //optional here because it is required only if buttons's CausesValidation property is set to false but it is true by default
if (!Page.IsValid)
{
return;
}
//write your login code here
}


0 comments:
Post a Comment
Note: only a member of this blog may post a comment.