Comparing 2 password fields if they are equal

Asked

Viewed 5,507 times

0

I have a password field and confirm password, I want to check if both are equal.

NOTE: There is an OFF autocomplete for the email field

$(document).ready(function () {
    $('#txtEmail').attr('autocomplete','off');

    if( $('#txtSenha').val() != $('#txtSenhaConfirme').val()   )
    {
        alert('Senhas diferentes');
        return false;
    }
});

Not from JS error, it just doesn’t work. NOTE: Even corrected the typing error, not yet validated.

  • http://meta.pt.stackoverflow.com/a/1911/101

  • 2

    Dude, after the different one is missing a "$(" ?

  • Unrelated, but don’t forget to also do a validation server side (Javascript may be disabled on the client, or even manipulated by an experienced user).

3 answers

5


There are some errors in your code, invalid syntax (missing $( in the #txtSenhaConfirme).

Anyway I doubt you want to do this check directly here $(document).ready(function () { 'cause that means basically "when the page just uploaded".

To check two values you can use the .value or .val() depending on whether you are using pure Javascript or jQuery.

So, and probably within a function, or an event like Submit, can do so:

if($('#txtSenha').val() != $('#txtSenhaConfirme').val()){
    alert('Senhas diferentes');
    return false;
}

Example:

$('form').on('submit', function () {
    if ($('#txtSenha').val() != $('#txtSenhaConfirme').val()) {
        alert('Senhas diferentes');
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
    <input type="text" id="txtSenha" />
    <input type="text" id="txtSenhaConfirme" />
    <input type="submit" />
</form>

  • ok, my failure to type, but it is still sending without validating!

  • @Dorathoto then has to put whole your code to be able to see where you might have other problems

2

The mistake is this:

$('#txtSenha').val() != '#txtSenhaConfirme').val()   

is forgetting a $( while the correct would be:

$('#txtSenha').val() != $('#txtSenhaConfirme').val()   

0

I’ve had problems in some browsers (IE7, IE6) with the .val(). It’s worth a try $('#txtSenha').text() != '#txtSenhaConfirme').text()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.