Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show submit button dynamically when email is valid

Tags:

jquery

I'm sure this should be easy, but I can't get it working.

html

<label for="email">Enter email for updates:</label>
<input type="text" name="email" id="email" placeholder="[email protected]" />
<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 it to be the best email validation, rather just a simple way to show users when form looks right.

Any help gratefully received.

like image 547
Jim Hyland Avatar asked Jul 28 '26 09:07

Jim Hyland


2 Answers

5 problems :

  1. a syntax error (you should have a look at your console when something doesn't work)
  2. you don't make the button disappear when the input isn't valid anymore
  3. you don't really test the input (thanks Eli)
  4. you don't check the "email" isn't empty
  5. some valid email are refused by your regex (try "valid email"@example.com)

My proposal 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 problem, I'd suggest you to read Stop Validating Email Addresses With Your Complex Regex.

like image 139
Denys Séguret Avatar answered Jul 30 '26 02:07

Denys Séguret


An assist to what dystroy said, there is a syntax error. But additionally, you're not setting your email variable when calling validateEmail. I also made the core more specific, per Steve's comments. Here's the updated code.

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

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

  });
like image 43
Eli Gassert Avatar answered Jul 30 '26 01:07

Eli Gassert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!