JQuery "Constrain" Plugin - Strange Javascript Error

Reference Information. Our web application uses the jquery.constrain.js plugin to handle the input of some text fields to allow for the addition of valid characters. This plugin allows various restrictions on data using regular expressions, whitelisting / blacklisting characters, etc. Until today, we have launched the 1.0 release of this module unchanged.

I noticed a few days ago that some text boxes still allow invalid input. For example, a text box with a numeric value allowed alpha characters, etc. It also displayed the javascript error "Object does not support this property or method". I traced it back to the following function in the jquery.constrain plugin.

    function match(item, input, e) {
        var arr = item.chars.split("");
        for (var i in arr) {
            var token = arr[i];
            if (token.charCodeAt(0) == e.which) {
                return true;
            }
        }
        if (item.regex) {
            var re = new RegExp(item.regex);
            if (re.test(String.fromCharCode(e.which))) {
                return true;
            }
        }

        return false;
    };

      

Debugging through this block of code, I have defined the following:

  • item - an object with two string properties: characters and a regular expression
  • item.chars is an empty string ("") at the time of failure.
  • arr, the result of item.chars.split ("") is, as expected, an empty array.

Here's where it gets weird. Even though arr is an empty array, the for loop assigns a valid value to i. The value "remove". So, we look into the loop. the token is obviously zero, because arr ["remove"] is null. Thus, token.charCodeAt (0) is being cast.

I fixed the error by adding an if statement around the for loop like below:

        if (arr.length > 0) {
            for (var i in arr) {
                var token = arr[i];
                if (token.charCodeAt(0) == e.which) {
                    return true;
                }
            }
        }

      

However, I am completely puzzled as to why this was necessary - is it an IE bug, a plugin bug, or am I just breathing wrong when I compile the application?

+1


a source to share


1 answer


You shouldn't use for (i in arr) to iterate over arrays. If scripts add methods to the Array prototype, they will also be repeated using a for (i in arr) loop. This is probably causing errors. You've probably added a script that modifies the Array.prototype chain.



Also read here under "Why you should stop using for ... for repeating (or never taking it)"
http://www.prototypejs.org/api/array

+1


a source







All Articles