views:

113

answers:

1

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 RegExs("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; }
        }
    }
);
A: 

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]);

}
Steve