简体   繁体   中英

Validate email address on keyup with jQuery

Im trying to validate an email address onkeyup only the following doesn't ever seem to return valid,

Can anybody see where i may be going wrong? I only have 1 input and my .first() selector is targeting that correctly...

$('.newsletter-signup input').first().keyup(function(){
    $email = $('.newsletter-signup input').first();
     function validateEmail($email) {
      var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
      if( !emailReg.test( $email ) ) {
        alert('foo');
      } else {
        alert('bar');
      }
    }
});

You code is bit incorrect, you can do this:

$('.newsletter-signup input').first().keyup(function () {
    var $email = this.value;
    validateEmail($email);
});

function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if (!emailReg.test(email)) {
        alert('foo');
    } else {
        alert('bar');
    }
}

In your code:

$email = $('.newsletter-signup input').first();

you are only getting the jQuery object of the first input not the value. Hence the validation is not working at all.

So, in order to get the value of the input element you can use:

 var $email = this.value;

as this here refers to the $('.newsletter-signup input').first() . So need to again call it and after that get the value from it. You can directly do that using this.value .

That's a lot of code to do very little, when all you're really trying to do is this:

$('.newsletter-signup input:first').on('keyup', function(){
    var valid = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(this.value);
    alert(valid ? 'foo' : 'bar');
});

Also note that setting the input type to "email" does the validation for you in browsers that support HTML5.

FIDDLE

$('.newsletter-signup input').first().keyup(function(){
    $email = $(this).val();// use val here to get value of input
     validateEmail($email);
});

   function validateEmail($email) {
          var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
          if( !emailReg.test( $email ) ) {
            alert('foo');
          } else {
            alert('bar');
          }
        }

reference .val()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM