Saturday, May 11, 2013

Client and Server side validations with the ASP.NET Validation controls


If you have ever wondered why it is always recommended to perform both Client side and Server side validation in your web application, the answer is it is very easy to bypass client side validation(easily emulated by downgrading the client target to downlevel in asp.net Page directive)  and submit invalid data in your forms. Needless to say, this could cause all kinds of errors to being vulnerable to cross-site scripting, sql injection etc.

The asp.net Validator controls support both client side and server-side validations by default and out of the box. However, what is not commonly known is that you have to write code to enforce the server side validation! So if you are using these validation controls without checking the Page.IsValid property, and the user disables client side scripting on her browser, then your page is still vulnerable and prone to errors. All it does by default on the server-side when we have these validators, is run the Page.Validate() routine to set the flag for the Page.IsValid property.

Most of the time we do not notice this behavior because we have JavaScript turned on and the client side validations fire and we think we are all set. So remember to check for IsValid from the button event handler which submitted the form, before using the data submitted in the form. Also, the Validate() function is run after the Page_Load event fires, so the .IsValid property is not available in the Page_Load event. Trying to even read that property to check if the data submitted are valid on the Page_Load would throw an exception. If you need to do so, call the Validate function before checking IsValid in Page_Load like so:

protected void Page_Load(object sender, EventArgs e)
{
        if (IsPostBack)
        {
            this.Validate();
            if (this.IsValid)
            {
                  //use your data
            }
       }
}

And one last caveat, in case you are not aware, the checkbox asp.net control do not support the ASP.NET validators, so you can't use them with this control.

No comments:

Post a Comment