Page.Validate() and Page.IsValid


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Page.Validate() and Page IsValid

Here we look at what is going on with using Page.Validate() and Page IsValid.

I'd obviously come across some situation years ago where I discovered that I needed to call both methods to ensure that validation had definitely occurred on the page, and ever since both method calls had been finding there way into my code more as a security wall, but perhaps in many cases were unnecessary, so I decided to find out exactly what's going on here.

Page.IsValid

You most definitely need to call Page.IsValid in your C# code where your expecting the page to be valid, such as in a Button click event handler for submitting a form. You might have gotten away without having to use for most of the time without realising what might happen. Say you have a form with some textboxes and a button to submit the form with some validators making sure textboxes have values etc. If the form doesn't have the values needed and you click submit, usually the validators have clientside validation enabled and so prevent the form being submitted. However,... should the browser have Javascript disabled, the client-side validation cannot run and the form can be submitted using the same button and the details send to the server. So in this case, client-side validation didn't run, and if you don't have a Page.IsValid check on the page, your code will run regardless of the fact validation did in fact fail when run on the server. So use the Page.IsValid method to check validation was successful, just in case the user disables Javascript in their browser.


if (Page.IsValid)
{
    ....
}


Page.Validate()

You can call validation manually in C# using the Page.Validate() method. You can either validate the whole page by calling Page.Validate(), or validate just one validation group by calling Page.Validate("MyValidationGroup"). But do you need to? Most of the time you'll find you don't.

Most controls have CausesValidation set to true by default, and therefore they will call Page.Validate() by default. In this particular scenario, validation occurs before the event handler for the control (eg Button click), so validation is automatically called before we get into our click event handler. However, if CausesValidation is set to false, then validation occurs after the event handler of the control, so in our button click event handler, validation won't have occured.

Another thing to consider with Page.Validate() is that it doesn't happen until after the Load event has finished. So if you need to have had your values validated in the Page_Load event or earlier, you'll need to manually call Page.Validate() to have the values validated first.


Page.Validate("MyValidationGroup");