Display submit button dynamically when email is valid

I'm sure this should be easy, but I can't seem to get it to work.

Html

<label for="email">Enter email for updates:</label>
<input type="text" name="email" id="email" placeholder="your@email.com" />
<button name="submit" type="submit">Submit</button>

      

Js

$(document).ready(function() {

  $('button').hide();

  $('input').keyup(function() {
    if( !validateEmail(email) ){ 
      $('button').show();
    }
  };

  function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test( email );
  }

});

      

I'm not looking for the best email validation, but just an easy way to show users when the form looks right.

Any help is gratefully received.

+3


source to share


3 answers


5 problems:

  • syntax error (you should take a look at the console if something doesn't work)
  • you don't make the button disappear when the input is invalid anymore
  • you don't really validate the input (thanks Eli)
  • you are not checking that the "email" is not empty.
  • Some valid email is rejected by your regex (try "valid email"@example.com

    )

My suggestion for the first four problems:



  $('button').hide();
  $('input').keyup(function() {
    if( validateEmail($(this).val()) ){ 
      $('button').show();
    } else {
      $('button').hide();
    }
  });

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

      

Demonstration

For the last issue, I suggest you read Stop validating email addresses with my complex Regex .

+6


source


Help what the distro says, there is a syntax error. But other than that, you don't set your variable email

when called validateEmail

. I also made the kernel more specific, according to Steve. Here's the updated code.



$('#email').keyup(function() {
    var email = $(this).val();

    if(validateEmail(email) ){ 
      $('button[type="submit"]').show();
    }
    else {
      $('button[type="submit"]').hide();
    }

  });

      

+3


source


Thanks dystroy, Eli Gassert and danronmoon. Various errors that you guys pointed out are downloaded here. For future reference, this is the code from your various fixes that now works for me:

$('button').hide();

$('input').keyup(function() {
    var email = $('#email').val();

    if( validateEmail(email)){ 
        $('button').show();
    } else {
        $('button').hide();
    }
});

function validateEmail(email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test(email);
}

      

0


source







All Articles