-3

I want to check if a phone number is valid, it has to be in JavaScript and the format can be in any country format, just needs to check if a phone number can be successfully sent to it?

jacobsieradzki
  • 1,108
  • 2
  • 10
  • 32
  • the best thing to do is "Not validate it" i mean, the user provided his phone number why make it angry with errors about invalid number? – Marco Acierno Aug 01 '14 at 16:40
  • This is not a duplicate of [this question](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation). That question is about validating with regex however this question is about checking if this phone number is an actual phone number or not. – Derek 朕會功夫 Aug 01 '14 at 16:44
  • You mean server-side Javascript, right? Because if you're trying to verify information about the user with an external source client-side, that amounts to just asking the user whether they're telling the truth. Which- surprise, surprise!- they'll say they totally are. If you do mean server-side, you should probably tag the question with the name of the javascript server software you're using (e.g. node.js). – Parthian Shot Aug 01 '14 at 16:48
  • Your best bet may be to either test the number against some database or use a 3rd party app that deals with calling/texting. You can't just "ping" a phone number as easily as you can ping an email, unfortunately. :/ – Casey Falk Aug 01 '14 at 16:49
  • I want a car. It has to be a Porsche, it just needs a new turbo engine? – Sterling Archer Aug 01 '14 at 16:50

2 Answers2

1

Normally, you mimic what people do with email:

  1. Use something like Twilio to call or text the number
  2. In the call or text, provide the user with a code
  3. Have the user enter the provided code on your website

If they can't provide the code you passed them, you refuse to take their phone number.

James Kingsbery
  • 7,298
  • 2
  • 38
  • 67
1

"Checking if a phone number is valid" is a vast subject. You may want to:

  • check that the number is actually a real number
  • just know that the number matches the rules for phone numbers is that country (i.e. valid prefixes, length...)
  • just be sure that it vaguely looks like a phone number (i.e. it has only digits and the usual separators)

There are tons of regexes and validation methods that might work for the third option.

For the second option, you'll need a library that has a database of formats in each country (note that this changes a lot over time, so you'll need to keep up to date).

One such library you can look at is Google's libphonenumber

For the first option, as James stated, you'll need to use something like Twilio to actually dial the number. At a minimum, you'll know whether the phone number works or not. If you want to validate that the user who entered it is the one answering the phone, you'll need to use some sort of code.

For mobile numbers, you may use text messages instead of calls.

jcaron
  • 17,302
  • 6
  • 32
  • 46