简体   繁体   中英

javascript error handling

I have a javascript function for checking errors which I am calling on OnClicentClick event of a button. Once it catch a error I want to stop execution of the click event. But in my case it always it always executes the onclick event.

Following is my function:

function DisplayError() {

        if (document.getElementById('<%=txtPassword.ClientID %>').value.length < 6 || document.getElementById('<%=txtPassword.ClientID %>').value.length > 12) {
            document.getElementById('<%=lblError.ClientID %>').innerText = "Password length must be between 6 to 12 characters";
            return false;
        }
        var str = <%=PhoneNumber()%>;
        if(str.length <10)
        {
            alert('<%=phoneNum%>'.length);
            document.getElementById('<%=lblError.ClientID %>').innerText = "Phone Number not in correct format";
            return false;
        }
    }

button html code:

<asp:Button runat="server" Text="Submit" ID="btnSubmit" ValidationGroup="submit" onclick="btnSubmit_Click" OnClientClick="DisplayError()"/>  

It should not execute the button click event once it satisfies any of the IF condition in the javascript function.

使用OnClientClick="return DisplayError();"

Use OnClientClick="if (!DisplayError()) return false;"

That way, if no error occurred, it will still postback, but only when an error occurs, it will return false, and cancel the postback.

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