0

I have used the following pattern for the regular expression for the phone number

pattern="[0-9 -+]+$";

The phone number may contain numbers, hyphen(-), space and plus(+). It works when i use numbers only. When numbers and alphabets are used it does not work.

What can be the problem, please do let me know.

Thanks in advance

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
user75472
  • 1,277
  • 4
  • 28
  • 53

4 Answers4

7

It is interpreting the - as part of a range. try this:

pattern="^[0-9 +-]+$";

The - either needs escaping (\-) or moving to the end like this (thanks Tim).

David M
  • 71,481
  • 13
  • 158
  • 186
4

Your regex will fail even after making the correction suggested by David. Because it matches any combination of one or more numbers and +, -. For example, it matches 99++++--12

Here is a better version that matches numbers in the format 999-999-9999 with an optional leading country code in the format +9999 (two to four digits long)

(\+\d{2,4}\s*)?(\d{3})-(\d{3})-(\d{4})
Amarghosh
  • 58,710
  • 11
  • 92
  • 121
  • Well, this won't match UK numbers unless you put hyphens in them in odd places. Correct international form for a London number, for example, would be +44 20 xxxx xxxx. – David M Nov 25 '09 at 17:49
  • Matching all locales is a difficult task (in India it is `+91 \d{10}`) - that's why I specifically said it matches 3+3+4 numbers. I was just pointing out the faults of `[0-9+-]` pattern. – Amarghosh Nov 25 '09 at 18:01
1

It needs to start with a ^ and the - needs to be escaped with a \

pattern=/^[0-9 \-+]+$/;

It needs to start with a ^ as that is an anchor for the start of the string, if you didn't it would validate strings that started with anything, as long as they ended with a number, space, - or +

- needs to be escaped as it is a special character and has a meaning other than -. While + is a special character, and if you want to treat it as a + outside a class it needs to be escaped, when inside a class only ]^-\ need to be escaped.

So outside of a class escape

.^$|*+?()[{\

And inside escape:

]^-\

However, most implementations allow you to escape all 12 special characters inside classes without error, and they will only give an error if you escape a non special character, which means that this (Note the extra \ before the plus) will also work fine.

pattern="^[0-9 \-\+]+$"



I always find that using a regex tester makes things easier as it allows me to see mistakes.

user187291
  • 53,363
  • 19
  • 95
  • 127
Yacoby
  • 54,544
  • 15
  • 116
  • 120
1

Since - (dash) is used as the range symbol inside brackets in regexp you need to either escape it, or place it last:

pattern="[0-9 \-+]+$";
// or
pattern="[0-9 +-]+$";

You might also want to begin the regexp with ^ to make sure the whole string matches it, not just the end:

pattern="^[0-9 +-]+$";
Mikael S
  • 5,206
  • 2
  • 23
  • 21