0

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>
laurence keith albano
  • 1,409
  • 4
  • 27
  • 59

2 Answers2

2

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/

Bart K
  • 324
  • 1
  • 8
1

I think you can use this fiddle link, does the work.

http://jsfiddle.net/o6d86xtw/1/

HTML

<label for="email" id="email">Hey!</label>
<input id="email" name="email" type="email" class="required" /> 
<span class="msg error">You shall not pass!</span>
<span class="msg success">You can pass!</span>

JQuery

var component = {
    input   : $('input[name="email"]'),
    mensage : {
        fields  : $('.msg'),
        success : $('.success'),
        error   : $('.error')
    }
},
   regex  = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/;

component.input.blur(function () {
    component.mensage.fields.hide();
    regex.test(component.input.val()) ? component.mensage.success.show() : component.mensage.error.show();
});

Note : I forked someone else's fiddle.

Gandalf the White
  • 2,415
  • 2
  • 18
  • 39