Search code examples
jqueryvalidationkeypress

Check input with keyPress


I have this js code, which checks my input field for correct email.

$(document).ready(function () {
$('.subscription-form input').keypress(function () {
    var inputEmail = $('#email-subscribe');
    var email = inputEmail.val();
    var button =  $('.subscription-form button');
    console.log(email.length);
    if (IsEmail(email)) {
        button.prop('disabled', false);
        inputEmail.css({'border':'none'});
    }
    else if (email.length < 1) {
        inputEmail.css({'border':'none'});
        console.log('enter');
    }
    else{
        button.prop('disabled', true);
        inputEmail.css({'border':'1px solid red'});
    }
});
});

Problem is that, when I write the correct email and then clear the input, my button is still active. I tried to check

if(input.email.length < 0)

then disable the button, but it only works when there is one character.

Please, help me to solve this problem.

HTML:

<form enctype="multipart/form-data" method="post" accept-charset="UTF-8"
                  action="/response.php"
                  class="text-center row subscription-form">
     <div class="col-lg-10 col-md-10 col-sm-10 col-xs-12 col-lg-offset-1 col-md-offset-1 col-sm-offset-1">
     <div id="output" class="col-lg-9 col-md-9 col-sm-8 col-xs-12"></div>
     <input id="email-subscribe" type="text" title="email" name="email"
                           placeholder="Enter your email*" class="col-lg-9 col-md-9 col-sm-8 col-xs-12 cnt-input">
           <button disabled class="btn request getjob col-lg-2 col-md-8 col-sm-10 hidden-xs">Sign up</button>
       <div class="col-lg-2 col-md-8 col-sm-10 col-xs-12 visible-xs margi-top-10">
           <button disabled class="btn request getjob">Sign up</button>
       </div>
  </div>
</form>

Solution

  • Try this Fiddle

    You shall use keyup rather than keypress to get the value entered since you will always get the string before the last entered character.

    It seems that when you empty the input using backspace the input value being set to an empty string which is passing the regular expression checking (assuming you are using a regex in function IsEmail).

    I have set the value as null in this case before passing the value to the function:

    var email = inputEmail.val() == "" ? null : inputEmail.val();

    No need for the else if condition since you always want to disable if the email fails.