1
votes

I am currently using a CustomValidator that uses JavaScript to validate either/or textbox has numbers in it. When I satisfy the validation the error, the message does not clear until submit. How can I fix this so it clears like my other out of the box validators? I am using ASP.NET with C#.

      <script type="text/javascript">

               function testnumbers(source, args) {
                   var s1 = document.getElementById('<%=arubaBox.ClientID%>').value; var s2 = document.getElementById('<%=shipBox.ClientID%>').value;


                   if (s1 == "" && s2 == "")

                       args.IsValid = false;
                   else if (s1 == "" && s2 != "")

                       args.IsValid = true;
                   else if (s1 != "" && s2 == "")

                       args.IsValid = true;
                   else if (s1 != "" && s2 !== "") args.IsValid = true;

               }

        </script>



   <asp:TextBox ID="aBox" runat="server" MaxLength="7"></asp:TextBox>



  <asp:CustomValidator 
    ID="CustomValidator1" runat="server"                       ClientValidationFunction="testnumbers" 
    ErrorMessage="CustomValidator"
     ValidationGroup="Contact"
     Text=" Please provide A # or Shipping Account #" 
    CssClass="errormessage"
     Display="Dynamic" >
    </asp:CustomValidator>

 &nbsp<asp:RegularExpressionValidator
        id="RegularExpressionValidator1"
        runat="server"
        ErrorMessage="Field not valid!"
        ControlToValidate="aBox"
        ValidationExpression="[0-9a-zA-Z]{5,}"
        ValidationGroup="Contact"
         />&nbsp

 <asp:RegularExpressionValidator 
    ID="NumErrAru" 
    runat="server"
    ControlToValidate="aBox"
     CssClass="errormessage" 
     ErrorMessage=" Numbers Only"
     ValidationExpression="^[0-9]+$"
     ValidationGroup="Contact" 
    Display="Dynamic" 
    Text=" Numbers Only">
    </asp:RegularExpressionValidator>
1

1 Answers

1
votes

You can control your page validation using both the Page_ClientValidate method and the Page_Validators collection:

function jsValidation(){
    Page_ClientValidate();
    $.each(Page_Validators, function(key, value) { 
        if( value.IsValid == false) {
            //- error in validation, locate failing input control 
            var oE = value.ControlToValidate; 
            //- you can for example set focus back to it, if needed
            oE.focus();
        }
    });
}

Use blur event to call your function when element loses focus :

$('#<%=element.ClientID%>').blur(function() {   jsValidation(); }); 

This implementation uses jQuery and hasn't been tested but should work pretty much as is. and you can also simply remove the jQuery interaction and use classical js if needed.

Hope this helps.