Reputation: 281
I have a page with a textbox control, a Custom Validator, a button to save entered data and code to handle the custom validation.
I set up a simple code test just to see how the Custom Validators work. I hope to add more validations that check multiple controls later. The same thing happens if I do add the ControlToValidate attribute for the textbox control. (I don't think I need a "ControlToValidate" attribute for this. I plan to validate multiple controls later. I can't put all the controls I am validating in that attribute.)
When I run my app, the save takes place and the validation is happeing - the message appears. I don't understand why the save isn't stopped when I enter "3" in the textbox I am checking. If the validation is happening, and if the IsValid = false, why is the save taking place?
Here is the Custom Validator:
<asp:CustomValidator ID="VisitSaveCustomValidator" runat="server" OnServerValidate="VisitSaveCustomValidator_ServerValidate" ValidationGroup="SaveVisit_val"></asp:CustomValidator>
Here is the button:
<asp:Button ID="SaveVisit_btn" runat="server" Visible="false" Text="- Save Visit -" ValidationGroup="SaveVisit_val" OnClick="SaveVisit_btn_Click" />
Here is the code for the Custom Validator:
protected void VisitSaveCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (VisitNumber_tbx.Text == "3")
{
args.IsValid = false;
VisitSaveCustomValidator.ErrorMessage = "The Visit Number cannot be 3.";
}
else
{
args.IsValid = true;
}
Please let me know if I need to add more code or more information. I thought this would be pretty straight-forward. I followed an example in a book and some online. I understand that the page is going back to the server to be validated. But, shouldn't the save be stopped since the IsValid = false?
It seems like the save is happening first, then the validation code executes, which causes the message to appear.
Thanks.
Upvotes: 0
Views: 3107
Reputation: 9224
I believe you may have to manually call the validate method.
VisitSaveCustomValidator.Validate();
Then check to see if it was valid.
VisitSaveCustomValidator.IsValid();
This can be put in the button click event.
Upvotes: 1