Search code examples
javascriptjqueryemailkeyup

Javascript - Remove the focus from input


I have an input that display a message for an invalid email format. This message disappear when the format is respected.

$('#id_email.form-control').keyup(function(){
$('span.error-keyup-email').remove();
var inputVal = $(this).val();
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputVal)){
  $(this).after('<span style="color:red;" class="error error-keyup-email">Invalid Email Format.</span>');
}
});

The code works very good. That's exactly what I wanted.

Problem : When I select an email that I have already saved by the browser (Normally it saves email or pseudo for the user). When I don't type my email and I select my email instead, the message still stays under the input, even if it's a correct email format.

Do you have an idea ?

I can give you more details if you want and thank you for taking time on my problem :)

Have a nice day :)


Solution

  • Try this:

    $('#id_email.form-control').on('input', function(){
    $('span.error-keyup-email').remove();
    var inputVal = $(this).val();
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(inputVal)){
      $(this).after('<span style="color:red;" class="error error-keyup-email">Invalid Email Format.</span>');
    }
    });
    

    keyup only fires once the key is pressed. input fires immediately when the value changes