2

I have a requirement that one of multiple fields is required. Using custom validator the even fires, false is returned, but no error message is display and the form validates.

What am I missing? I have tried with and without ValidationSummary.

Thanks!

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ></asp:CustomValidator>

<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"  runat="server" ForeColor="Red" Font-Size="X-Small" Font-Bold="true" />


protected void validatePhone(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = string.IsNullOrEmpty(txtCellPhone.Text) && string.IsNullOrEmpty(txtHomePhone.Text) ? false : true;
    }

3 Answers 3

1

You have to set the ControlToValidate to some TextBox.

<asp:CustomValidator ID="CustomValidator1" OnServerValidate="validatePhone" EnabEnableClientScript="false" runat="server" ErrorMessage="Home or Cell Phone is Required" ControlToValidate="txtHomePhone"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Setting ControlToValidate will not validate if the control is empty. Since I am validating multiple controls this will not work.
1

Check out this article. Basically you need to wire up the client side validation. Add the following just before the closing form tag changing the control names as needed:

<%-- This configures the validator to automatically--%> 
<%-- update when either of these controls is changed --%>
<script type="text/javascript">
   <!--
      ValidatorHookupControlID("<%= MyControl1.ClientID %>", 
      document.getElementById["<%= CustomValidator1.ClientID %>"]);
      ValidatorHookupControlID("<%= MyControl2.ClientID %>", 
      document.getElementById["<%= CustomValidator1.ClientID %>"]);
   //-->
</script>

Alternatively use this control

Comments

1

Issue was completely my fault. On my submit button the final thing I do is a Response.Redirect. The message was coming up, but then the Thank you page was being presented. Now only doing the Response.Redirect if the customvalidator returns true.

1 Comment

You should only do process the code if Page.IsValid = true. That checks all validators in the ValidationGroup are valid. Otherwise you can bypass validation by messing with the JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.