0

How can i validate a phone number with plus sign optional only at the beginning and after that any number of digits with number only.

I tried this:-

/^\+(?:[\d]*)$/

How will be the modification

VeNaToR
  • 49
  • 2
  • 7
  • The regex is `^\+?\d+$`. In HTML `pattern` attribute, it looks like `pattern="\+?\d+"`. If you need to limit the number of digits to a specific amount replace `\d+` with `\d{n}` where `n` is the exact number of digits you want. – Wiktor Stribiżew Jul 28 '23 at 11:30

2 Answers2

5
/^\+?(?:[\d]*)$/

The questionmark tells that the plus sign can be there or not. However, your expression can be optimized quite a bit:

/^\+?\d+$/ 

I changed the * to a + as the expression would match just a plus sign. \d* suggests that it should match 0 or more digits.

Here's a demo on Regexr.

rdiz
  • 6,136
  • 1
  • 29
  • 41
  • 1
    There's a lot of unnecessary stuff in there, the shortened version would be `/^\+?\d*$/`. – Biffen Apr 10 '15 at 07:20
-1

Expression for plus, hyphen and numbers in a phone number

^\+?\d+-?[0-9]+-?[0-9]+$
Andy A.
  • 1,392
  • 5
  • 15
  • 28
test dev
  • 1
  • 1
  • 2
    Welcome to SO. - Please give a little explanation to your example. – Andy A. Jul 14 '21 at 05:29
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Jul 25 '21 at 18:00