views:

30

answers:

2

Hi All,

I am trying to use the Jquery Validate Plugin and I was able 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

+1  A: 

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

naugtur
@naugtur Excellent post.. Sorry I just type in everything so I forgot to place comments. Although I still have one query, on every addmethod that I am seeing, I always see this line this.optional(element). What is meant by that line? I just added it thinking that it is always required.
Mark Estrada
@Mark It's a part of the validation plugin I suppose. And it checks if the field is set to optional so that it won't validate an optional field. You don't need this I suppose. But I never used the validation plugin
naugtur
A: 

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;
        }
    }
Ken Egozi