Dreams
Dreams

Reputation: 8506

How to write a regex only allow numbers and "(", ")", "-"

Below is my regex but it seems not working

/[0-9\-\(\)]/.test(str)

when I test

 /[0-9\-\(\)]/.test('(12321)213213d')

It will return true

Upvotes: 0

Views: 633

Answers (5)

Jeetendra Chauhan
Jeetendra Chauhan

Reputation: 1977

/^[\d\(\)\-]+$/.test('(12321)213213d')

^ start, $ end, \d for digit and ()-,

I think you are looking for telephone number matcher, if your answer is yes then this is not right regex for it.

for telephone matcher visit this link

Upvotes: 0

Ian Mundy
Ian Mundy

Reputation: 376

I believe adding input beginning/end characters will fix this. Like

^[0-9\-(\)]$/.exec('(12321)213213d')

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Your current regex just checks that any one character in the string matches the character class. Add anchors and a quantifier: /^[0-9\-\(\)]+$/

  • ^ - "Beginning of input" anchor
  • $ - "End of input" anchor
  • + - Require one or more of the preceding thing

Mind you, "()" will match that regex. :-)

Upvotes: 5

mpen
mpen

Reputation: 282845

What you're actually testing is if any of those characters are in your test string. You want to check if it contains only those characters. To do that, you need to say from start ^ to finish $ it only contains those chars.

e.g.

/^[0-9()-]+$/.test('(12321)213213d')

Upvotes: 7

Daniel A. White
Daniel A. White

Reputation: 190915

You need to repeat it with either * or +. You also need to anchor it with ^ and $ to contain the whole string.

console.log(/^[0-9\-\(\)]+$/.test('(12321)213213d'));
console.log(/^[0-9\-\(\)]+$/.test('(12321)213213'));

Upvotes: 4

Related Questions