Regex for 16-digit phone number

Viewed 400

I am working on a chat application where user have to fill the form before he/she begins the chat. Validation of each form field happens once user enters the value in respective form field. One of the form field is phone number and for which I wrote a regular expression as following.

var phoneRegex = RegExp(/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,10}$/im);

Regex should return 'true' for following phone numbers

  • +11234567890 - 10 digits with area code
  • 1234567890 - 10 digits
  • 233445678912 - 12 digits
  • 2334456789122222 - 16 digits

My chat application works for first 3 numbers but doesn't work for 16 digit phone number. I am not a huge fan of regex and have limited understanding of it hence I want to to know if my regex has any fault? And if yes then how can I fix it?

2 Answers

How about this?

It checks for the optional leading '+', followed by a 16 digit number, and if that fails, it checks for any of a 10, 11, or 12 digit number.

One thing I'm not entirely clear on is if that plus is always optional though. Also I think you might mean country code instead of area code? If I'm wrong about that, then this regex is no good.

^\+?(\d{16}|\d{10,12})

Results on Regexr (without the leading ^, for example purposes)

enter image description here


Alternatively you can try this

It's a bit more strict about things

^(\d{16}|\+?\d{11}$|\d{10,12})

Since your phone field is a continuous string of digits (or at least that’s what I understood from your post) why do you need to use RegExp?

Just use basic logic, something like this...

var N='1234567890';

var Valid=((isNaN(N)===false)&&(Number(N)>1000000000)&&(Number(N)<9999999999999999));

alert(Valid);  // test it.
Related