Ensuring emails match, using onkeyup event

529 views Asked by At

I have this html form code:

$("#email").blur(function(){
  //check to two here.
  if ($("#email").val() != $("#email_repeat").val())
  {
    $("#email_repeat").keyup(function(){
      if ($("#email").val() != $("#email_repeat").val()) {
        // emails don't match
      }
    });
  }
});
<label for="email">Email address:</label>
<input type="email" id="email" name="email" placeholder="[email protected]" 
       title="Enter email address" required>

<label for="email_repeat">Confirm email address:</label>
<input type="email" id="email_repeat" name="email_repeat" placeholder="[email protected]" 
       title="Confirm email address" required >

I want to make sure they match in real time and I know i need to use the on key up event.

What am I missing here?

1

There are 1 answers

1
Yeldar Kurmangaliyev On

You are defining a keyup event every time on check. It is absolutely wrong and illogically.

It is like you say:

If user leaves focus on 'email' textbox and emails don't match 'email_repeat' then add an event to 'email_repeat' so if keyup occurs, if email don't match...

This is how it should be done:

$("#email").on('keyup', ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").on('keyup', ValidateEmails); // validated after user clicks a key

$("#email").blur(ValidateEmails); // Remove these two if you don't want it to be
$("#email_repeat").blur(ValidateEmails); // validated when a user loses focus

function ValidateEmails()
{
    if ($("#email").val() != $("#email_repeat").val())
    {
        // emails dont match
    }
}

That's how I say:

If user leaves the focus or clicks a key on either 'email' or 'email_repeat' textboxes then check if emails are not equal