-2

I need to validate a email field with jquery but the program doesn't work.

   var email_form=$('#email');
        if(email_form!=null){
console.log("HI");
            $('#email').on('input', function(){
                console.log("show ");
            });
        }

The program prints "HI" but it doesn't print in "show".My purpose is to every time that an user writes a character in a email field I must validate this text. Anyone can help me?

adsds
  • 123
  • 1
  • 12
  • Please provide a reproducible demo. – nicael Jan 18 '16 at 15:05
  • whilst validating email on the client side is a good idea, you must implement a server side validation also to help prevent against xss attacks and unwanted email addresses. – MMK Jan 18 '16 at 15:14
  • 1
    also here's a post on how to validate email addresses properly http://stackoverflow.com/questions/46155/validate-email-address-in-javascript – MMK Jan 18 '16 at 15:16

1 Answers1

0

Assuming you have the following html:

<form>
   <input type="text" name="email" id="email">
</form>

Add the following jquery:

$(document).ready(function() {
   $('form').on('keydown','#email',function() {
      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,}))$/;
      if(re.test($("#email").val())) {
          //email is correct
      } else {
          //email is incorrect
      }
   })
});
  • Since the email field obviously exists at load time, you can just to `$('#email').on('keydown',function...` – mplungjan Jan 18 '16 at 15:17