user1829823
user1829823

Reputation: 375

Comparing two passwords with Jquery

I'm trying to compare two passwords that a user will enter when trying to register but whenever a password is equal to that of the confirmed password is still throws the error passwords don't match. There's two stages to this if no password is entered then a error is presented that works fine, but the second stage comparing two password the errors is always true and presents it self.

if ($('#password').val() == "") {
     $('.error').append("<li> Please enter a pasword </li>");
     error = true;
    } else if ($('#password') !== $('#password1')) {
     $('.error').append("<li> You password does not match the confirmed password </li>");
     error = true;
    }

Upvotes: 0

Views: 2906

Answers (2)

mastaBlasta
mastaBlasta

Reputation: 5850

You could improve your code a bit to make it faster. You should cache dom queries and insert error text once. Whether or not there are errors is determined by the emptiness/non-emptiness of the errors array.

var FormHandler = {
    errors: [],
    validate: function(){/*...function to run all validations */}
    checkPassword: function(){
        var pass = $('#password').val();
        if (!pass || pass === "") {
           this.errors.push("Please enter a pasword");
        } else if (pass !== $('#password1').val()) {
           this.errors.push("You password does not match the confirmed password");
        }
        this.printErrors(); // or continue to next form validation
    },

    //...more validation functions...

    printErrors: function(){
       if(this.errors.length){
           $('.error').html("<ul><li>" + this.errors.join("</li><li>") + "</li></ul>");
       }
    },
}

Might seem like overkill but it is faster and much easier to maintain as your forms get longer and validations more complex.

Upvotes: 0

Jon
Jon

Reputation: 437386

You also have to use .val() when comparing the passwords between themselves:

else if ($('#password').val() !== $('#password1').val())

Upvotes: 2

Related Questions