4

I must be doing something wrong. I can't seem to execute my CustomValidator's ServerValidate method.

I've got a Visual Basic ASP.NET page with a CustomValidator...

<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
    ControlToValidate="TextBox1"
    ErrorMessage="Friendly message goes here."
    Display="Dynamic" />
<asp:Button ID="Button1" runat="server"
    Text="Submit"
    CausesValidation="True" />

For this test, I've got the validation set to always fail...

Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    args.IsValid = False
End Sub

But, when the button is clicked, the CustomValidator1_ServerValidate() method never executes!

Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Page.Validate()
    If Page.IsValid Then
        'it executes the code here!
    End If
End Sub

Not even if I explicitly validate that control...

CustomValidator1.Validate() 'does nothing?

What am I doing wrong?

4 Answers 4

9

Add the property:

 ValidateEmptyText="True"
1
  • That's fixed it. Thank you. I'm using the CustomValidator as a conditional RequiredFieldValidator. The TextBox is or is not required depending on the values of other controls on the page. So, it needs to be bale to validate empty text. Commented Jan 26, 2009 at 21:56
2

Are you putting the validator control submit button in the same validation group?

1

Firstly, You seem to be missing the OnServerValidate attribute in your markup above.

Secondly, I would check to ensure that CustomValidator1_ServerValidate has been set up as an eventhandler for the ServerValidate event for Textbox1. I have had occasions where I have changed the name of the validate method in the markup and code-behind, but the IDE has not auto updated the subscribing method name passed to the eventhandler delegate

1

I know it's a daft question (or might sound like it!). But have you actually entered or changed the value in the textbox? I think the validator won't trigger without the contents of the textbox changing.

1
  • My TextBox is empty. That's the problem. Commented Jan 26, 2009 at 21:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.