Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirm Password with jQuery Validate

I'm trying to use jQuery validate plugin to confirm my password entry.

However, I don't want it to be a required field.

Just IF a user wants to change the password, they would need to confirm it.

If not, both fields shouldn't be validated.

jQuery('.validatedForm').validate({
    rules: {
        password: {
            required: true,
            minlength: 5
        },
        password_confirm: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        }
    }
}); 

This is working perfectly, but again, both fields are required.

I would like to have this optional, in case someone just wants to change for instance their email or username and leave the password alone.

like image 858
ldrocks Avatar asked Feb 05 '13 08:02

ldrocks


3 Answers

Remove the required: true rule.

Demo: Fiddle

jQuery('.validatedForm').validate({
    rules: {
        password: {
            minlength: 5,
        },
        password_confirm: {
            minlength: 5,
            equalTo: "#password"
        }
    }
});
like image 86
Arun P Johny Avatar answered Nov 06 '22 18:11

Arun P Johny


Just a quick chime in here to hopefully help others... Especially with the newer version (since this is 2 years old)...

Instead of having some static fields defined in JS, you can also use the data-rule-* attributes. You can use built-in rules as well as custom rules.

See http://jqueryvalidation.org/documentation/#link-list-of-built-in-validation-methods for built-in rules.

Example:

<p><label>Email: <input type="text" name="email" id="email" data-rule-email="true" required></label></p>
<p><label>Confirm Email: <input type="text" name="email" id="email_confirm" data-rule-email="true" data-rule-equalTo="#email" required></label></p>

Note the data-rule-* attributes.

like image 36
Rob W Avatar answered Nov 06 '22 19:11

Rob W


It works if id value and name value are different:

<input type="password" class="form-control"name="password" id="mainpassword">
password: {     required: true,     } , 
cpassword: {required: true, equalTo: '#mainpassword' },
like image 8
Krishna Kumar Avatar answered Nov 06 '22 17:11

Krishna Kumar