What is Page.IsValid and page.validate in asp.net?

Dear friends, In previous article we were learn Difference between DataTable and DataSet in dot net. and Date and Time formats in asp.net using C-Sharp, vb.net

Today we are going to learn very important interview question, What is the difference between Page.Isvalid and Page.Validate ?

Asp.net provides validation controls like RequiredFieldValidator, RangeValidator, CompareValidator, RegularExpressionValidator and CustomValidator etc. for validate user input data from input forms before post data from client to server. To make sure only correct validated data should be submitted.

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.

Page.Validate is a method, Page.IsValid is a property. The former forces validation of one or all validation-groups (if no group is specified), the latter Page.IsValid is a boolean type property (flag) to check whether page validation succeeded or not and returns the result of this validation.

Validate():

Instructs any validation controls included on the page to validate their assigned information.

Validate(String):

Instructs the validation controls in the specified validation group to validate their assigned information.

You don't need to call Page.Validate manually if the control that caused the postback has CausesValidation set to true(default).

Validate Method is invoked automatically by controls themself, that have the CausesValidation property set to true.

Note that the Button control’s CausesValidation property is true by default.

We can check Page.IsValid property only after calling the Page.Validate() method, or set the CausesValidation property to true which is by default true for button control.

Lets take and example for user login form as follows.

UserLogin.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserLogin.aspx.cs" Inherits="DateTimeFormatApp.UserLogin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p><label>User Name <span style="color:red">*</span></label><asp:RequiredFieldValidator ID="rfvUserName" runat="server"
                        ControlToValidate="txtUserName" ErrorMessage=" is required" ValidationGroup="vgLogin"
                        ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator></p>
            <asp:TextBox ID="txtUserName" ValidationGroup="vgLogin"  runat="server"></asp:TextBox>         </div>
         <div>
            <p><label>Password <span style="color:red">*</span></label> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                        ControlToValidate="txtPassword" ErrorMessage=" is required" ValidationGroup="vgLogin"
                        ForeColor="#FF3300" SetFocusOnError="True"></asp:RequiredFieldValidator></p>
            <asp:TextBox ID="txtPassword" ValidationGroup="vgLogin" TextMode="Password" runat="server"></asp:TextBox>
        </div>
        <div>
            <p><label>&nbsp;<asp:Literal ID="litmsg" runat="server"></asp:Literal></label></p>
            <asp:Button ID="btnLogin" ValidationGroup="vgLogin" runat="server" CausesValidation="false" Text="LogIn" OnClick="btnLogin_Click" />
        </div>
    </form>
</body>
</html>

Please note:

<asp:Button ID="btnLogin" ValidationGroup="vgLogin" runat="server" CausesValidation="false" Text="LogIn" OnClick="btnLogin_Click" />

In above control CausesValidation = "false"

UserLogin.aspx.cs

using System; namespace DateTimeFormatApp { public partial class UserLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnLogin_Click(object sender, EventArgs e) { if (!IsValid) return; // Your validated code goes here txtUserName.Text = txtPassword.Text = string.Empty; litmsg.Text = "User is verified."; } } }

Above code will throw excepton on run application and hit login button as follows.

System.Web.HttpException occurred HResult=0x80004005 Message=Page.IsValid cannot be called before validation has taken place.
It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
Source=StackTrace:
at DateTimeFormatApp.UserLogin.btnLogin_Click(Object sender, EventArgs e) in c:\users\kanha ji\documents\visual studio 2017\Projects\DateTimeFormatApp\DateTimeFormatApp\UserLogin.aspx.cs:line 16

We can add Page.Validate(); method before validate form as follows or set CausesValidation="true" for btnLogin control.

UserLogin.aspx.cs

using System; namespace DateTimeFormatApp { public partial class UserLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } 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 if (!IsValid) return; // Your validated code goes here txtUserName.Text = txtPassword.Text = string.Empty; litmsg.Text = "User is verified."; } } }

VB.net

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 If Not Page.IsValid Then Return End If 'Write your login code here End Sub

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories