Hbaecklund Hbaecklund - 7 months ago 18
Javascript Question

How to trigger function on false?

I have an input form that I want to validate email adresses (or just an @ sign). But I only want validation when it's wrong, so remove everything from before the else statement in the jquery snippet?

EDIT

When the user input is wrong, in this case not an emailadress, inform the user.

HTML

<form onsubmit="validate(); return false;">
<p>Enter an email address:</p>
<input id="email">
<button type="submit" id="validate">Validate!</button>
</form>
<br>
<h2 id="result"></h2>


jQuery

function validateEmail(email) {
var re = /@/;
return re.test(email);
}

function validate(){
$("#result").text("");
var email = $("#email").val();
if (validateEmail(email)) {
$("#result").text(email + " is valid :)");
$("#result").css("color", "green");
} else {
$("#result").text(email + "is not valid :(");
$("#result").css("color", "red");
}
return false;
}

$("form").bind("submit", validate);

Answer

You can use like this:

function validate(){
  $("#result").text("");
  var email = $("#email").val();
  if (!validateEmail(email)) { //email is invalid
    $("#result").text(email + "is not valid :(");
    $("#result").css("color", "red");
    //call a function to trigger
    return false;
  }
}
Comments