Introduction:
Difference between Page.Isvalid and Page.Validate is also important interview question.
When we create a web form for taking user input e.g. login form or contact us
form in asp.net we have to
validate the user input before submitting to server so that only validated data
could be submitted to server.
Javascript validations are
not secure. We should use Page.Validate() method and Page.IsValid property
to validate data.
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
}
VB.NET Code
Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click
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 Not Page.IsValid Then
Return
End If
'Write your login code here
End Sub
Note: It is recommended to
check Page.IsValid before submitting to server.
0 comments:
Post a Comment