ASP.NET Validation

ASP.NET has validation controls used to ensure that user input is... yes you’ve guessed it....valid! But their exact behavior can seem a bit of a mystery (most notably to me when presenting at SLIDE7 ;-)).

As such I’ve been on a mission to discover and document their behavior and present it in a clear and concise manor so here goes....

  • All validation controls offer both client and server side validation.
  • The client side validation is implemented in Javascript.
  • If Javascript is switched off on the client browser then server side validation provides back up.
  • If Javascript is enabled and the user input cannot be validated the page never posts back therefore saving bandwidth.
  • If Javascript is enabled and the user input can be validated then the user input is re-validated on the server side.

However if validation fails on the server side code is still executed whereas if validation fails on the client side no server side code runs because the page is never posted back.

This means that if there is code that you don’t want to execute if server side validation fails this code MUST be wrapped in a conditional statement that looks something like this: if (this.isValid)

The purpose of this behavior is to allow you to have code that executes if validation succeeds, validation fails or in both scenarios.

I fell over on this with my demo at SLIDE7. I was showing how the page only posted back if the user input was validated on the client side. I then decided to switch client side scripting off in my browser to prove that the server side validation was happening however my page errored when I entered invalid input. This happened because my code was still executing and the input was invalid so caused an error. Below is the code which broke and the correct way to implement the desired result.

The wrong way to do it:

    1: protected void Button1_Click(object sender, EventArgs e)
    2:        {
    3:            //code will execute regardless of validation
    4:            int myint = Convert.ToInt32(TextBox1.Text);
    5:            int result = myint * 2;
    6:            Label1.Text = result.ToString();
    7:         }

The right way to do it:

    1: protected void Button1_Click(object sender, EventArgs e)
    2:        {
    3:            //Code within IsValid conditional will execute only 
    4:            //if page validates server side
    5:            if(this.IsValid)
    6:            {
    7:                int myint = Convert.ToInt32(TextBox1.Text);
    8:                int result = myint * 2;
    9:                Label1.Text = result.ToString();
   10:            }
   11:            //Any code outside of the IsValid conditional will 
   12:            //execute regardless of validation
   13:        }

Hopefully this makes sense but if you have any questions feel free to comment.

Technorati Tags: ASP.NET, Validation, Microsoft, SLIDE7