I have id’s validation method, each id can contain only [a-z0-9_] case insensitive characters. [^a-z] seems working, but I want to append [^0-9] but it’s not work. How one string pattern should looks like?
function foo() {
testUserIds = ['id23425860',
'yulka_rdtska',
'im?sel=2000000001',
'im?sel=2000000002'];
for (id in testUserIds) {
document.write(isUserIdValid(id) + '\r\n');
}
}
function isUserIdValid(user_id) {
var patt = new RegExp('[^a-z]', 'ig');
return patt.test(user_id);
}
The problem is that you are using a
for-inconstruct instead of a properforloop. Use[^a-z0-9_]as your regular expression and iterate correctly over your array.In JavaScript, don’t iterate over arrays with
for (elem in arr), as that syntax’s purpose is to iterate over properties of an object. Instead usefor (var idx=0; idx<something; idx++).Note that the way you have setup your function, it returns the opposite of what it says. You are checking for invalid characters, so return the inverted: