问题
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:
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");
    }
});
    来源:https://stackoverflow.com/questions/2700295/using-jquery-validator-plugin-how-to-use-dynamically-created-name-attributes-to