user17274
user17274

Reputation: 11

How to trigger asp.net customvalidator with javascript

I am trying to trigger asp.net custom validator with java script but it is not triggering. Other validators such as required field validators are getting triggered from the below-shown code. Can anyone tell me what is wrong in the below code or why it is not triggering

<script type="text/javascript">
    function CheckValidation(btn) {
        var valid = false;
        if (Page_ClientValidate('RtRegValGrp')) {
            alert('valid');
            __doPostBack(btn.name, "");
         } else {
             alert('not valid');
         }
     }
</script>

<asp:TextBox ID="txtCompanyName" runat="server" MaxLength="100"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
    ControlToValidate="txtCompanyName" 
    ValidationGroup="RtRegValGrp" 
    ErrorMessage="Company name is required !"
    ForeColor="red" Display="Dynamic" />
<asp:CustomValidator ID="txtCompanyNameValidator" runat="server"
    ControlToValidate="txtCompanyName"
    ValidationGroup="RtRegValGrp"
    OnServerValidate="BlackListValidator" 
    ForeColor="Red" Display="Dynamic">
</asp:CustomValidator>

<asp:Button ID="Button1" runat="server" CssClass="goldBtn" Text="SUBMIT" 
    OnClientClick="CheckValidation(this); return false;" 
    OnClick="Button1_Click" />

//server side code
protected void BlackListValidator(object source, ServerValidateEventArgs args)
{
    args.IsValid = false;
}

Upvotes: 0

Views: 3168

Answers (1)

freefaller
freefaller

Reputation: 19963

Your CustomValidator is currently set up with server-side validation code only... there is no way for the client-side ASP.Net code to be able to know the result of the validation without a post-back.

For it to be client-side, you need to replicate the validation code in javascript (you must leave the server-side code in place for security reasons) and then set the ClientValidationFunction property...

<asp:CustomValidator ValidationGroup="RtRegValGrp" ID="txtCompanyNameValidator"
  ForeColor="Red" OnServerValidate="BlackListValidator" Display="Dynamic"
  ControlToValidate="txtCompanyName" runat="server"
  ClientValidationFunction="BlackListValidatorFnc" />

<script>
  function BlackListValidatorFnc(src, args) {
    args.IsValid = false;
  }
</script>

Upvotes: 2

Related Questions