There is a common misconception regarding ASP.NET validators among many ASP.NET developers, even seasoned ones. Many developers think that by adding a validator to a form and associating it to a control will guarantee the validity of that control’s value. They are SO wrong!
Try the following:
Create a new form with a Textbox, Required field validator and a Button. Associate the Validator with the Textbox, and set its ErrorMessage property to anything you want:
<div>
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqfTxt"
ControlToValidate="txt" ErrorMessage="*" runat="server">
</asp:RequiredFieldValidator>
</div>
<div>
<asp:Button ID="btn" runat="server" Text="Submit" />
</div>
Assuming you haven’t disabled browser’s Javascript, the browser will not let you submit the form by clicking the Button, unless you’ve entered something into the Textbox.
Now, let’s disable client-side validation by setting Validator’s EnableClientScript to false and run the form again. Everything still looks pretty correct, pushing the Button will post the form the server, and after a round-trip, the page will return with the error message:
Let’s now see what is happening on the server. Create an event handler for the Button-click event and click the F9 key when the cursor is inside the handler function to create a break-point. Hopefully, by now you already understand that the break point will be hit. The conclusion is that the ASP.NET Page will do the full life-cycle, including entering every event on the page, even though the input is not valid.
Unfortunately, many developers don’t understand this and tend to trust the validators to stop page execution. Well, as you already see, validators don’t stop the page execution, even if the input is invalid.
The thing is, validation is one of the steps of the Page lifecycle. It happens right after the Page loading is complete (LoadComplete event) and before processing event handlers. The Page’s Validate() method recursively cycles through each of the controls implementing IValidator interface, calling its Validate() method and verifying validator’s IsValid property. In case one of the page validators is invalid, the method assigns false to IsValid property of the page.
It is your own responsibility to verify Page.IsValid before executing any piece of business logic that assumes valid input.
protected void btn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
this.txt.BackColor = Color.Azure;
}
}
Another thing to remember: Page.IsValid is accessible only after running Page.Validate() method which is invoked implicitly somewhere after Page_Load. In case you keep all of your logic in a Page_Load event handler (which is highly discouraged!), call the Page.Validate() before checking the Page.IsValid.
Have fun and happy validations!