Sharath Kumar
Sharath Kumar

Reputation: 145

Custom method with jQuery Validation plugin

Im trying to work with custom validation in Jquery. All the coding part is right,but i am not getting where its going wrong...here is the part of code.

Password:<input type="password" id="pnameTxt" name="pnameTxt" placeholder="Enter Password" size=12 class='required'><br>
Confirm Password:<input type="password" id="pnameTxt2" name="pnameTxt2" placeholder="Retype Password" size=15 class='required passwordCheck'><br>

Custom validation method:

 $.validator.addMethod("passwordCheck",function (value,element){
          return value==$("#pnameTxt").val(); 

        }, 'Password and Confirm Password should be same');

Upvotes: 5

Views: 48154

Answers (2)

Sparky
Sparky

Reputation: 98718

Your code is working. You also have to assign the rule to your field when you initialize the plugin with .validate().

Working DEMO: http://jsfiddle.net/KrLkF/

$(document).ready(function () {

    $.validator.addMethod("passwordCheck", function (value, element) {
        return value == $("#pnameTxt").val();
    }, 'Password and Confirm Password should be same');

    $('#myform').validate({ // initialize the plugin
        rules: {
            pnameTxt2: {
                passwordCheck: true
            }
        }
    });

});

HOWEVER, you do not need to write a custom method for this functionality. The jQuery Validate plugin already has an equalTo rule, and here's how to use it.

Working DEMO: http://jsfiddle.net/tdhHt/

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            pnameTxt2: {
                equalTo: "#pnameTxt" // using `id` of the other field
            }
        },
        messages: {
            pnameTxt2: {
                equalTo: "Password and Confirm Password should be same"
            }
        }
    });

});

Upvotes: 34

Marcel Gwerder
Marcel Gwerder

Reputation: 8520

Have u initialized the validation plugin correctly? When I put the html in a form and then initialize the plugin it works as expected.

<form id="test">
Password:<input type="password" id="pnameTxt" name="pnameTxt" placeholder="Enter Password" size=12 class='required'><br>
Confirm Password:<input type="password" id="pnameTxt2" name="pnameTxt2" placeholder="Retype Password" size=15 class='required passwordCheck'><br>
<input type="submit">
</form>
$.validator.addMethod("passwordCheck",function (value,element){
      return value==$("#pnameTxt").val(); 

    }, 'Password and Confirm Password should be same');

$('#test').validate();

Upvotes: 1

Related Questions