laurence keith albano laurence keith albano - 3 months ago 10
HTML Question

Validate an email and display message inside a span tag

I have this simple code here about the input type email. I have some reference about validating an email when user clicks the button. Here's the reference http://stackoverflow.com/questions/46155/validate-email-address-in-javascript

HTML code

<html>
<body>
<div class="form-group">
<input class="form-control" placeholder="Email" name="email" id="email" type="email" required>
<span id="checkEmail"></span>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<html>


I tried the script to validate and display a message in the span tag id="checkEmail" using keyup event function but it doesn't seem to work. Does my syntax is incorrect? Please help.

Its Script

<script>
//Email Regular Expression function
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}

//Email Validate function
function validate() {
$("#email").keyup(function() {

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

//UPDATE
$(document).ready(function() {
$("#checkEmail").keyup(validate);
});
}
</script>

Answer

Your code works for me, all I needed to do is to call

validate();

anywhere on document load to actually bind the events.

(which means you might want to move the binding outside the validate function, to not re-bind it anytime you click/use the function)

edit: I have prepared a fiddle for you: https://jsfiddle.net/caz9o53e/