Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 426
Sharath Kumar Avatar asked Mar 23 '13 16:03

Sharath Kumar


2 Answers

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"
            }
        }
    });

});
like image 168
Sparky Avatar answered Sep 30 '22 13:09

Sparky


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();
like image 27
Marcel Gwerder Avatar answered Sep 30 '22 14:09

Marcel Gwerder