开发者

Jquery Custom Validate Plugin AddMethod on Dynamic Forms

I am trying to use the Jquery Validate Plugin and I was ab开发者_JS百科le to figure out how to use it on static fields.

My problem is on how to used it on my dynamic forms. I created a fiddle to discuss my problem. Hope you can have patience on reading this. The fiddle link is here

Now, here's what I want to do, validate the Machine ID entered on each text box and make sure that it is unique. Say you enter ABCD-123 twice, the system should alert you that it is not unique.

Hoping somebody could lend me a hand on this. Thanks


first of all - put comments in your code while you write.

the error is here:

 var arrElements = $(".machineID");

arrElements is always empty, there is no element with machineID class

and your each doesn't work. I refactored it http://jsfiddle.net/PaTJ4/

Your code could use some more fixes, it's a bit too complicated for that task. But now it works.

good luck


I've improved on your version - when a duplication is detected, any one of the duplicated fields should be marked as invalid, and should be able to be changed in order to fix the problem. So, you'd need to revalidate all other fields every time (using validator.element()), but avoid a recursion (using validator.validatingOthers).

I'll post the code for checkMachineIDs here for completeness:

    function checkMachineIDs(element){
        if($(element).val() != ""){
            var arrElements = $("#machineList .machineID"); 
            var $element = $(element);
            var validator = $($element[0].form).validate();
            if(arrElements.length > 1){
                var valid = true;
                arrElements.not('#'+$element.attr('id')).each(function() {
                  var current = $(this); 
                  if (current.val() == $element.val())
                    valid = false;
                });
                if (!validator.validatingOthers) {
                    validator.validatingOthers = true;
                    arrElements.not('#'+$element.attr('id')).each(function() {
                        validator.element(this);
                    });
                    if (valid) validator.element($element);
                    validator.validatingOthers = false;
                } 
                return valid;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜