开发者

jQuery Validation Plugin - Using validator.addMethod in Loop

I have a good number of regular expressions used for validation. Instead of manually typing in many addMethods for each regex, I tried using a loop. I have the below simulated struct to hold the regex name, RegExp object and validation message.

function RegExs(exprName, expr, exprVM) {
    this.exprName = exprName;
    this.expr = expr;
    this.exprVM = exprVM;
}

After populating an array of the above, I loop through and do the addMethods, to make things much easier to update and maintain:

for (i in pgRegExs) {

    $.validator.addMethod(pgRegExs[i].exprName,
        function(value, element) {
            return this.optional(element) || pgRegExs[i].expr.test(value);
        },
        function(value, element) { return pgRegExs[i].exprVM; }
    );
}

However, the validator does not seem to be picking up the regular expression. It does get the name and validation message. Any clues?

Update: Correction: The validator is picking up the function array, but the last one in the array is applied to every input. So if I have:

pgRegExs = [
  new RegE开发者_如何转开发xs("addrCustName", regExAddrCustName, regExAddrCustNameVM),
  new RegExs("addrStreet", regExZipCodeLng, regExZipCodeLngVM),
  new RegExs("addrCity", regExZipCodeLng, regExZipCodeLngVM),
  new RegExs("zipcodeLng", regExZipCodeLng, regExZipCodeLngVM),
  new RegExs("emailFormat", regExEmailAddr, regExEmailAddrVM),
  new RegExs("emailLength", regExEmailAddrLen, regExEmailAddrLenVM)
];

The emailLength regular expression is applied to every input. Below, addrCustName should be applied to the input field, but emailLength is used instead.

$("[id$='_tbFName']").rules("add",
    {
        required: true,
        addrCustName: true,
        messages: {
            required: "First name required",
            addrCustName: function(value, element) { return regExAddrCustNameVM; }
        }
    }
);


I needed to use a closure:

for (i in pgRegExs) {

    (function(pgRegEx) {

        $.validator.addMethod(pgRegEx.exprName,
            function(value, element) {
                return this.optional(element) || pgRegEx.expr.test(value);
            },
            function(value, element) { return pgRegEx.exprVM; }
        );

     })(pgRegExs[i]);

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜