6

I'm trying to learn javascript Regex and I've hit a problem.

I'm trying to validate with the following rules.

Allow only:

Numbers 0-9 
( 
) 
+
-
(space)

I have come up with the regex below to handle this:

/[0-9\)\(\+\- ]+/i

The following matches but shouldn't do because it contains a @ symbol:

+0@122 0012

I'm using the below to test: (Returns true)

/[0-9\)\(\+\- ]+/i.test("+0@122 0012")

Thanks.

2
  • 3
    There's no constraints, it matches anything with a matcing character, add ^ and $. Commented Jul 30, 2014 at 14:30
  • 2
    +1 because the clarity of your regex question is rare here. Commented Jul 30, 2014 at 14:34

1 Answer 1

15

Your regular expression won't match the "@" character, but it doesn't have to in order for the .test() call to return true. There just has to be a match somewhere in the string.

If you want to insist that the entire string matches, you have to use ^ and $ anchors.

/^[0-9)(+ -]+$/i.test("+0@122 0012")
Sign up to request clarification or add additional context in comments.

1 Comment

D'oh! You beat me by about three seconds!

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.