Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to block server side event firing under button click in JavaScript. I have set a JavaScript function in onclientclickevent() and even if it return false set after showing the validation server event is getting fired. The sample code is below.

What I have tried:

Code is as below:
JavaScript
function Test() {
               var regex = /^(?=.*\d)(?=[^A-Za-z]*[A-Za-z])(?=.*[-!@#$%._]).{8,20}$/

               //Validate TextBox value against the Regex.
               var isValid = regex.test(document.getElementById('<%=txtNewPass.ClientID %>').value);
               alert(isValid);
               if (!isValid) {
                   alert("Password must be at least 8 characters, and must include at least one special character, one alphabet, and one numeric digit.");
                   return;
               }

       }

ASP.NET
<asp:Button ID="btnSave" runat="server" Style="position: static" Text="Save" Enabled="true"
                                   Width="111px" CssClass="NeST_BUTTON"  OnClick="btnSave_Click" Height="26px" OnClientClick="javascript:Test();"/>
Posted
Updated 1-Feb-22 5:32am
v2

1 solution

If you want to stop the button from submitting the form, then you need to block the form from being submitted.
ASPX
OnClientClick="Test(event);"
JavaScript
function Test(event){
    ...
    if (!isValid) {
        alert("...");
        event.preventDefault();
        return;
    }
}
Event.preventDefault() - Web APIs | MDN[^]

However, you don't need custom Javascript to validate that an entered value matches a particular regular expression; just use a RegularExpressionValidator instead:
ASPX
<asp:RegularExpressionValidator runat="server"
    ControlToValidate="txtNewPass"
    ValidationExpression="(?=.*\d)(?=[^A-Za-z]*[A-Za-z])(?=.*[-!@#$%._]).{8,20}"
    ErrorMessage="Password must be at least 8 characters, ..."
/>
RegularExpressionValidator Class (System.Web.UI.WebControls) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900