ASP.NET Validation Controls: How to Disable It
Posted by triaslama on December 2, 2008
Validating an input is a common need, sometimes we want a field must be filled, a field must be in a specific range, or an input must follow a special pattern. ASP.NET has a bunch of validation controls that make our job a little bit easy. Despite all of the ease of use offered by ASP.NET validation controls, sometimes -just maybe- we need to disable it.
One important thing we must if we use ASP.NET validation controls is: what actions will trigger validators? One of the answer is button click! (The other maybe Postback action). With that in mind, we can take a conclusion that every click event of asp.net button (<asp:Button />) by default will always trigger validation controls to take the appropriate action.
Let’s say I want to disable RequiredFieldValidator against a TextBox control for one action, and enable it for another action, how can I accomplish this? Consider I have textbox control and two button controls (previous button and next button accordingly). I want if previous button clicked it goes to previous page and doesn’t fire the required field validator. Well, the solution is really simple.
By default each button control will trigger validation control to take an action, unless we override CausesValidation property to false! Yes, that is the solution set CausesValidation property of previous button to false and it will solve the problem.
I drop the code below:
In above example I assume that PreviousTest.aspx and NextTest.aspx is exist.
Now left the TextBox blank and click ‘Previous’ button. Compare with: left it blank and click ‘Next’ button. To more realize what the role of CausesValidation property change it to true, refresh the page, and do the same thing as before.