Daniel Hoelbling-Inzko talks about programming

Validation Controls in ASP.NET

Posted by Daniel Hölbling on July 15, 2008

So, yesterday I noticed something funny while doing some data-driven ASP.NET programming.

There are those really great Validation controls that really reduce the amount of code you need to write on average input forms.

So, imagine you have quite usual code like this:

<asp:TextBox runat="server" ID="MyTextbox"></asp:TextBox><br />
<asp:RequiredFieldValidator ControlToValidate="MyTextbox" runat="server"><br />
    Textbox shouldn't be empty

<asp:Button runat="server" Text="Submit" OnClick="Submit_Click" />

This will result in a simple form with a textbox and a submit button. The handler code for the button looks like this:

public void Submit_Click(object sender, EventArgs e)
    this.Title = "Hello World";

Now, if you click on the button while leaving the textbox blank, you'll see the red message that the field needs to be filled.

If you disable Javascript in your browser, the handler code will get executed without getting validated!

Actually, the validation is done solely on the client if you don't manually check for the Page.isValid property on the Webform.

So, here is the revised handler code:

public void Submit_Click(object sender, EventArgs e)
    if (this.IsValid)
        this.Title = "Hello World";

This isn't something unknown, MSDN points it out on some occasions. But yet, something you might overlook too easily.

Keep this in mind when working with validator controls, hope this helps!

Filed under net, programmierung
comments powered by Disqus

My Photography business


dynamic css for .NET