Always check Page.IsValid (plus validation related thoughts)

Posted by: Jotekes Blog, on 02 Feb 2007 | View original | Bookmarked: 0 time(s)

This sounds probably obvious, so why am I blogging about this? Well, I attended some discussion on newsgroups where one user had misunderstanding that ASP.NET doing server-side validation automatically would be enough so that you don't need to check Page.IsValid. And that isn't always true. Consider following:

Sample

<asp:TextBox ID="txtExpectingIntegers" runat="server" />
<asp:RequiredFieldValidator ID="reqINteger" runat="server"
ControlToValidate="txtExpectingIntegers" ErrorMessage="Insert something!" />
<asp:CompareValidator ID="cmpValInt" runat="server"
ControlToValidate="txtExpectingIntegers" Operator="DataTypeCheck"
Type="Integer" ErrorMessage="Please enter an integer!" />
<asp:Button ID="btnSend" runat="server" Text="Try it out"
OnClick="btnSend_Click" />

<asp:Label ID="lblMessage" runat="server" />

// Code

protected void btnSend_Click(object sender, EventArgs e)
    {
        //Testing for Page.IsValid here helps...
        // if(!Page.IsValid)return;

        try
        {
            int val = Int32.Parse(txtExpectingIntegers.Text);
            lblMessage.Text ="We got an integer " + val.ToString();
        }
        catch(Exception ex)
        {
            lblMessage.Text = "Exception while parsing the integer:" +
ex.ToString();
        }
    }
 

So?

If you now open it in in any normal browser with js enabled, of course with standard scripts enabled it's catched & validated. But go now and disable javascripts in your browser. Then type something non-number to the TextBox and you'll see it blow, as Button's click is handled normally as if there would be no validation. E.g nothing prevents the Button's click event from running unless *you* check for the outcome of the validation (validation message are displayed but page executes as-is). Think if it would be a database operation dependant on the input user enters...

So to summarize: you do want to check IsValid at the server. Just running validation isn't enough, you do need to know did it pass or not to decide
what's next (to let ValidationSummary or something to display a nice message)

What if?

OK, this might be stupid idea but I'll say it anyway.

That got me thinking, since MS has already automated (or defaulted) lots of tasks in v2.0, especially with data source controls, why wouldn't they add something like automatic form validation?

To put it shortly; when you have xxxButton which triggers validation, and in case the validation fails, could the default action in that case be *not* to run Button’s Click event, but instead throw a Page level event "Page_ValidationFailed" taking in the relevant validation related arguments.

That would remove user’s need to check Page.IsValid at server-side in case he/she has automatic validation enabled. Say you could control the behavior with something like

<% @Page EnableAutomaticFormValidation=”True|False” %>

or in web.config

<pages enableAutomaticFormValidation="true|false" />

where True is the default. What I'm thinking as reasoning is

  • it adds more “default” security to validation process
  • It lowers the bar to understand the how ASP.NET validation works -- you wouldn’t need to check Page.IsValid
  • You still have total control when you disable the automatic thing
  • global Page_ValidationFailed | ValidationSucceeded events remind me about how you work with Enterprise Services (Page_CommitTransaction, Page_AbortTransaction)
  • It gives you central point to handle the outcome of the validation (alternative could be single event ValidationComplete where it is flagged if it succeeded or not)

Downsides or something not supporting the idea would be:

  • No matter what, it is quite simple to just check Page.IsValid
  • Introducing new events are also performance factors
  • There are always things that people don't get right away, no matter what - you can't control that
  • It could be annoying when you expect the Click event to be raised and it won't be
  • If you prefer the old idea, you need to turn it off at page or at web.config level

What do you think?

 

Share this post: email it! | bookmark it! | digg it! | reddit! | kick it! | live it!

Advertisement
Free Agile Project Management Tool from Telerik
TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.
Category: ASP.NET | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 2114 | Hits: 50

Similar Posts

  • Multi-Page Applications in Silverlight more
  • Displaying XPS Documents in Silverlight more
  • Disabling the Submit Button Until a CheckBox is Checked more
  • ASP.NET MVC Plan 9 Sample more
  • How to manage ASP.NET validation from Javascript with jQuery more
  • Web Cast and Digging Deeper more
  • Finding Untitled Page Titles more
  • Disabling the Submit Button Until a CheckBox is Checked more
  • Page Switching With Parameters (the short version) more
  • Tradeoffs In Script Registration more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD