-3

I need a regex to validate phone number without plus (+) sign for example

46123456789,46-123-456-789,46-123-456-789

number should be 11 digit rest of should ignore

i am currently using this Regex /([+]?\d{1,2}[.-\s]?)?(\d{3}[.-]?){2}\d{4}/g

its not correct at all

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Umer Zaman
  • 181
  • 3
  • 16

3 Answers3

1

About the pattern you tried:

Using this part in your pattern [+]? optionally matches a plus sign. It is wrapped in an optional group ([+]?\d{1,2}[.-\s]?)? possibly also matching 12 digits in total.

The character class [.-\s] matches 1 of the listed characters, allowing for mixed delimiters like 333-333.3333

You are not using anchors, and can also possible get partial matches.


You could use an alternation | to match either the pattern with the hyphens and digits or match only 11 digits.

^(?:\d{2}-\d{3}-\d{3}-\d{3}|\d{11})$
  • ^ Start of string
  • (?: Non capture group for the alternation
    • \d{2}-\d{3}-\d{3}-\d{3} Match either the number of digits separated by a hyphen
    • | Or
    • \d{11} Match 11 digits
  • ) Close group
  • $ End of string.

Regex demo

If you want multiple delimiters which have to be consistent, you could use a capturing group with a backreference \1

^(?:\d{2}([-.])\d{3}\1\d{3}\1\d{3}|\d{11})$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

I am not sure how is the input looks like. But based on your question I supposed you want to trim it and match it with regex?

trim your input.

string.split(/[^0-9.]/).join('');

and you can match it with this regex:

((\([0-9]{3}\))|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$
Johan Syah
  • 21
  • 4
0

I would have this function return true or false and use as is.

function isPhoneValid(phone) {
  let onlyNumbers = phone.replace(/[^0-9]/g, "");
  if (onlyNumbers.length != 11) console.log(phone + ' is invalid');
  else console.log(phone + ' is valid');
}

isPhoneValid('1 (888) 555-1234');
isPhoneValid('(888) 555-1234');
tinymothbrain
  • 412
  • 2
  • 6