简体   繁体   中英

How to call JavaScript function when ASP.Net validators succeed?

I have a webform with ASP.Net controls and Validators for them setup into a group. I am trying to execute some JavaScript that occurs only when the validators succeed, to prevent the user from going onto the next step of the form without completing the requirements.

However, I cannot seem to get this to work properly. The JavaScript either executes without validation completing, or the JavaScript won't execute when validated successfully. I have a sneaking suspicion that this is due to the combination of HTML Required="true" tags, and ASP.Net validators behaving differently.

ASP.Net

<asp:TextBox ID="EmailAddress" runat="server" TextMode="Email" Required="true" ValidationGroup="Group1" />

<asp:TextBox ID="Password1" runat="server" TextMode="Password" Required="true" ValidationGroup="Group1" />
<asp:RegularExpressionValidator ID="valPassword" runat="server" ControlToValidate="Password1" 
    ErrorMessage="Your password doesn't meet the strength requirements" 
    ValidationExpression="^(?=.*\d)(?=.*[a-z])(?=.*[/W_].*)(?=.*[A-Z]).{8,255}" 
    ValidationGroup="Group1" ></asp:RegularExpressionValidator>

<asp:TextBox ID="Password2" runat="server" TextMode="Password" Required="true" ValidationGroup="Group1" 
/>
<asp:CompareValidator runat="server" ControlToCompare="Password1" ControlToValidate="Password2"  
    ErrorMessage="Your entered passwords do not match." ValidationGroup="Group1" />

<asp:Button ID="btnNext" runat="server" Text=">" OnClientClick="pgNext();" ValidationGroup="Group1" />

JavaScript

function pgNext() {
    if (Page_ClientValidate("Group1")) {
        $('.register-page1').css('display', 'none');
        $('.register-page2').css('display', 'block');
    } else {

    }
}

Call your page validator, then check if page is valid, then finally call your js function. In your button click event:

 Page.Validate("validationGroupNameHere");

 if(Page.IsValid)
 {
   // click code here
   
  //then call your js function
  Page.RegisterStartupScript(Page, Page.GetType(), "callMe", " jsFunctionNameHere();", true);
 }


 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM