Question

I have the following code. When I press my save button, three requiredfieldvalidators run fine and work properly. However my custom validator does not work. It does not fire the event at all. I have standard text boxes and a validationsummary control. Is there any reason why it might not be working?

<asp:RequiredFieldValidator runat="server" ControlToValidate="txtForename" Display="None" ErrorMessage="Must enter a valid first name." />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtSurname" Display="None" ErrorMessage="Must enter a valid last name." />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" Display="None" ErrorMessage="Must enter a valid e-mail address." />

<asp:CustomValidator runat="server" OnServerValidate="CheckAtLeastOnePhoneNumber" 
        ErrorMessage="Must enter at least one phone number." Display="None" 
        ValidateEmptyText="True" />

<script runat="server">
    void CheckAtLeastOnePhoneNumber(Object s, ServerValidateEventArgs e)
    {
        if (txtMobileNumber.Text.Equals("") &&
            txtWorkNumber.Text.Equals("") &&
            txtHomeNumber.Text.Equals(""))
        {
            e.IsValid = false;
        }
    }
</script>
Was it helpful?

Solution

I fixed it.

The custom validator control is a server-side check, and so the other validators (which are client side) execute first. This is a little bit misleading as the validationsummary control usually displays all validator errors.

Assuming the name, email etc. were valid, only then would it submit to the server and come up with the validation error.

OTHER TIPS

That's right. That's the way it works. If you want a custom validator to also work in the browser, you need to implement your custom validation in JavaScript and define the method in the control's ClientValidationFunction property. Then it will show up with the client-side errors in the validation summary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top