jQuery-将验证规则动态添加到多个文本框

问题描述:

我正在尝试将验证规则动态添加到多个文本框.这是js:

I'm trying to add a validation rule to multiple textboxes dynamically. Here's the js:

            //validate form.
            $("#SubmitForm").validate();
            $("input[id*=Hours]").rules("add", {
                number: true,
                messages: {
                    number: "Please enter a valid Hours"
                }
            });

这会将规则应用于ID中带有小时"的页面上的第一个文本框,但随后不会将其应用于其他任何文本框.

This applies the rule to the very first textbox on the page with "Hours" in the id but then it doesn't apply it to any of the other ones.

有人知道这是怎么回事吗?

Anyone know what's wrong here?

谢谢, 贾斯汀

您可以使用

You can add the rule to each item matched by the wildcard selector with .each(), like this:

$("#SubmitForm").validate();
$("input[id*=Hours]").each(function() {
    $(this).rules("add", {
        number: true,
        messages: {
            number: "Please enter a valid Hours"
        }
    });
});

希望这会有所帮助!