views:

1181

answers:

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?

+1  A: 

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

Rob
My TextBox is empty. That's the problem.
Zack Peterson
+4  A: 

Add the property:

 ValidateEmptyText="True"
Gavin Miller
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.
Zack Peterson
+2  A: 

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

Kon
+1  A: 

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

Russ Cam