2

Here's the problem:

The ecommerce system we uses generates a line item for each product purchased. It gives line item's quantity input the name attribute "qty0", "qty1", "qty2", and so on as the line items go down the page.

I need to check these qtyX inputs for validity, but I don't know how to pass either the name attribute as a relative attribute of another attribute like a class, or pass a regex to the validate plugin to find all the quantity fields.

Here's the validate code:

var validator = $("#formName").validate({
    rules: {
        qty: { customMethod: true}// qty
        },//rules

    messages: {
        qty: {customMethod: "NOPE"}
    },

    errorPlacement: function(error, element) {
            error.appendTo("#itemQuantityError");
    },

});

Here's a sample of the input that gets generated:

<td ><input name="qty1" value="6" size="5"></td>

Thank you!!

1 Answer 1

7

You could generate the rules and the messages dynamically:

var rules = new Object();
var messages = new Object();
$('input[name^=qty]:text').each(function() {
    rules[this.name] = { required: true };
    messages[this.name] = { required: 'This field is required' };
});

var validator = $("#formName").validate({
    rules: rules,
    messages: messages,
    errorPlacement: function(error, element) {
        error.appendTo("#itemQuantityError");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. That is perfect. I got pulled off of this project and so I haven't had time to address this issue again... you know how that goes?? ;) Thanks again.
Just to chime in, this works pretty well for me where, instead of iterating over a jquery object, I can iterate over an array of names as well. jQuery validation can even handle complex names when you setup the rules this way. So, let's say I have an array like ["input1", "input2"], I can say $.each(myArray, function(i,v) { rules["namespace."+v] = {required: true}; }); And it will create rules for all my fields with ids like "namespace.input1".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.