A prototype function for finding out if an array contains an element. Works for both JS and Actionscript.
1 2 3 4 5 6 7 8 9 | Array.prototype.contains = function(value) { for (var i=0; i<this.length; i++) { if (this[i] == value) return true; } return false; } |
Your comment form cut off most of my question -
Question? Can this function ” Function: Array.contains() ” be used to identify spam URL’s within a form fields content (say strings www; Http; /url; href; etc.) and then use your brilliant validation.js script to Alert to the user that such content is not allowed ?
Hey Martin,
Sorry for the wait!
No, I wouldn’t use the Array.contains() function for that particular purpose – it’s really just for arrays, not string pattern matching like you need. What I’d suggest is looking into the regular expression option (reg_exp) added in the last version of the validation script (http://www.benjaminkeen.com/software/js_validation/)
That would be a much better match! Regular expressions are pretty scary at first, but they’re a *staggeringly* useful tool once you wrap your head around them!
All the best –
Ben
Wouldn’t you want to return true right away, since there is no need to continue iterating through the array since you’ve validated that there is an item matching that value?
Hey Raine.
You’re quite right. I was indoctrinated by some professor a long, long time ago who told me to never have more than return statement. Not a bad idea, but I should have added a “break”. I’ll just update the function, thanks!
- Ben