Custom method with jQuery validation plugin

I am trying to work with custom validation in jQuery. All of the encoding is correct, but I don’t understand where this is going wrong ... here is the 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');
+5
source share
2 answers

Your code is working. You should also assign a 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 your own method for this function. The jQuery Validate plugin already has a rule equalToand here is 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"
            }
        }
    });

});
+34
source

? html form, initialize the plugin, , .

<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();
+1

All Articles