Simon Price
Simon Price

Reputation: 3261

Javascript - textbox validation on ASP.Net button click

When I click the asp.net button as per the below code, it goes into my js file, and gets the function as I need, however if it fails validation it still goes through with the postback as if it were valid.

the asp.net button

<asp:Button ID="bttnSend" runat="server" OnClientClick="DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />

the javascript

function DoValidation(parameter) {
console.log("validating");
var valid = true;
var emailTo = document.getElementById("txtEmailTo").value;
if (emailTo.length < 1) {
    alert("Please select at least one recipient to send an email to");
    valid = false;
}

console.log(valid);
if (valid == true) {
    __doPostBack('bttnSend', parameter);
}

};

I would be grateful if someone could please tell me what i need to change and what to so that the validation doesnt allow the postback if it fails.

thanks

Upvotes: 0

Views: 1439

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to prevent the default action of button when condition fails.

Modify your function to return true/false

function DoValidation(parameter) {
    var valid = true;
    var emailTo = document.getElementById("txtEmailTo").value;
    if (emailTo.length < 1) {
        alert("Please select at least one recipient to send an email to");
        valid = false;
    }
    return valid;
};

The use the return value

<asp:Button ID="bttnSend" runat="server" OnClientClick="return  DoValidation()" Text="Send" CssClass="btn btn-primary margin30" />

Upvotes: 4

Related Questions