-2

I am using the following regex for telephone number validation. It is allowing all the cases except one.
^(\+?\ *[0-9]+)([0-9 ]*)([0-9 ])*$|(^ *$)

The conditions are
1. Allow numeric values
2. Allow plus sign only in the beginning

The regex is getting failed while I enter the first character as plus sign. If I have entered a number after the plus sign it will work. My requirement is the form should valid while entering the plus sign as the first character. I am using a Angular reactive form. So error will fire entreating the first character itself.

Thanks in advance.

Vimal
  • 2,767
  • 3
  • 19
  • 24
  • I recommend that you change your UI. A good pattern to follow here would have separate boxes for each component in the phone number. For starters, you could have a prefix box, which e.g. could either be empty or contain a single `+` sign. Then, apply your number regex logic to a second box. – Tim Biegeleisen Feb 04 '19 at 07:38
  • It does not work because this part `(\+?\ *[0-9]+)` expects at least 1 digit. Note that all that follows is optional and this part `(^ *$)` also matches an empty string. You might take a look at this page for [phone number validation](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation). – The fourth bird Feb 04 '19 at 07:44
  • Just add `[+]?` after the carat `^` at the beginning. Here's an example cobbled from elsewhere on SO. https://regex101.com/r/SRMz4w/1 – JGFMK Feb 04 '19 at 07:55
  • NB: the `([0-9 ])*` is useless. It will never capture anything. – trincot Feb 04 '19 at 07:58

1 Answers1

1

Try this ^(\+?)([0-9 ]*)([0-9 ])*$|(^ *$).

But what you had initially is also fine but as you said its not your requirement, try the above one

dileepkumar jami
  • 2,185
  • 12
  • 15