user2110618
user2110618

Reputation: 119

validate .net page using javascript

I am using the below code to validate the asp.net page while the button click.i want to check the text box is empty or not. If its empty means it doesn't go to the server side click event. If it has some value means process go to code behind click event.

Now i met small problem. If text box value == "" means it return the error message and go the server side click event. How do i prevent the server side post back when the condition is false.

 <asp:Button ID="btn_add" runat="server" Text="Submit" OnClick="add_new" OnClientClick="valid_name();"/>

 function valid_name() {
        var name = document.getElementById('<%= txt_name.ClientID%>').value;
        if (name == "") {
            alert('Error Alert : You must enter a valid name !.');
            return false;
        }
        else {
            return true;
        }
    }

Upvotes: 2

Views: 553

Answers (1)

Aristos
Aristos

Reputation: 66641

Just change this code

OnClientClick="return valid_name();"

adding the return on your call will affect if the click will pass or stop, and that because you actually return true/false from the function depend from the input but that return is not affect the button with out the return in the direct call on the button.

Upvotes: 4

Related Questions