0

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;
}
1
  • .match(/[A-z0-9@.\-()#_$]/) Commented Oct 14, 2015 at 20:35

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

The requirement is "Trying to create a regex that allows only Letters, Numbers, and the following special characters"
Thanks. Updated accordingly. I was going off the question itself, skipped past the comments.
0

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 $.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.