user1511579
user1511579

Reputation: 1537

Jquery validation to match email fields

i have this html code:

<p>
 <label for="email">E-mail</label>
 <input id="email" name="email" placeholder="ex: [email protected]"/>
</p>        
<p>
<label for="email_alt">E-mail Alternativo</label>
<input id="email_alt" name="email_alt" />
</p>

and i want to validate if the emails match in running time.

i found the code below in one of the posts here in stackoverflow and i understand that #author_email and #author_confirm_email are the id's of the inputs. And as far was i know .blur is to trigger the alert in running time. but i'm not understanding that ".email" that trigger the function. What can i use there considerating the code i have?

   $(".email").blur(function(){
  //check to two here.
  if ($("#author_email").val() != $("#author_confirm_email").val())
  {
    //do something
  }
});

Upvotes: 0

Views: 1616

Answers (3)

Aletheios
Aletheios

Reputation: 4020

If you want to check the fields at runtime (i.e. while the user is typing), you have to use the keyup event (this event is fired each time a user has pressed and released a key):

$("#email_alt").keyup(function(){
    if ($("#email").val() != $("#email_alt").val()) {
        // emails don't match
    }
});

Didn't test this, but actually it should work like that.

You might want to add some further validation, e.g. prevent empty fields and assure valid email addresses (as GTSouza suggested).

Upvotes: 1

Chris
Chris

Reputation: 440

The blur event is triggered whenever the object loses focus (ie someone presses tab or clicks the next input box). Note that the "." signifies a class, whereas "#" is an ID. So in that code, every time something with a class name of "email" loses focus, that validation function is called.

Upvotes: 2

GTSouza
GTSouza

Reputation: 365

//

input#email

//

input#email-confirm

//

function IsValidEmail(a){var b=/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;return b.test(a)}

var validate = true;
$('input[name*="email"]:visible', $(this)).each(function(index, field){
            if(!IsValidEmail($(field).val()) && validate){
                $(field).focus().addClass('invalid');
                validate = false;
                return false;
            }

            var confirm = $('#'+$(field).attr('id')+'-confirm');
            if(confirm.size() > 0){
                if($(field).val() != $(confirm).val()){
                    $(field).focus().addClass('invalid');
                    validate = false;
                    return false;
                }
            }
        });

Upvotes: 0

Related Questions