Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
ASP.NET: Using Page.IsValid
From Wiki
Summary: Using Page.IsValid
When you use Validator controls on a page, they automatically write out some javascript to force the user into following the validation you create. Let's take this simple example:
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default7.aspx.vb" Inherits="Default7" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>Untitled Page</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator
- ID="RequiredFieldValidator1"
- runat="server"
- ErrorMessage="Please Enter A Value"
- ControlToValidate="TextBox1"
- Display="Dynamic">
- </asp:RequiredFieldValidator>
- <asp:Button ID="Button1" runat="server" Text="Button" />
- </div>
- </form>
- </body>
- </html>
What this will do is make sure that the user enters a value into the TextBox before the page is submitted to the server. However, as this validation is done via javascript what happens if the user doesn't have javascript capabilities or has decided to disable it? Well, let's try it. Disable javascript in your browser, add the following code for the button click event and submit the form with no value in the TextBox:
- Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
- Response.Write("I fired...")
- End Sub
What you will have seen is that although the "Please Enter A Value" message appears, the button click has also fired and executed the Response.Write and you will see the "I fired..." message. This is obviously not very good as now the user was able to submit the form without adhering to our validation controls. Fortunately, this is easy to fix with the Page.IsValid method. Change your code behind to include this check and then re-run the test:
- Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
- If Page.IsValid Then
- Response.Write("I fired...")
- End If
- End Sub
You'll now notice that we have fixed the problem as the error message appears and you do not see the "I fired..." message.
This Hack is part of the ASP.NET Hacks collection



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.