Reputation: 299
I know my code is wrong, I am trying to test for certain characters, and as long as they exist for each char in the input field, it will pass true, otherwise pass false.
function isChar(value) {
//Trying to create a regex that allows only Letters, Numbers, and the following special characters @ . - ( ) # _
if (!value.toString().match(/@.-()#_$/)) {
return false;
} return true;
}
Upvotes: 0
Views: 67
Reputation: 1160
The \w class will catch the alpha numeric. The rest you provided (but properly escaped):
function isChar(value) {
return value.toString().match(/[\w@.\-()#_\$]/) ? true : false
}
Upvotes: 0
Reputation: 36438
Assuming you're actually passing a character (you don't show how this is called), this should work:
function isChar(value) {
if (!value.toString().match(/[a-z0-9@.\-()#_\$]/i)) {
return false;
} else
return true;
}
console.log(isChar('%')); // false
console.log(isChar('$')); // true
console.log(isChar('a')); // true
If instead you're passing a string, and wanting to know if all the characters in the string are in this "special" list, you'll want this:
function isChar(value) {
if (! value.match(/^[a-z0-9@.\-()#_\$]*$/i)) {
return false;
} else
return true;
}
console.log(isChar("%$_")); // false
console.log(isChar("a$_")); // true
Upvotes: 2
Reputation: 21565
Characters that have meaning in regexp need to be escaped with \
. So for example you would replace $
with \$
and so on for the other such characters. So the final regexp would look like:
@.\-()#_\$
Since you need to escape both the -
and the $
.
Upvotes: 0