jibjab3344
jibjab3344

Reputation: 69

How do I write a function that takes in a telephone number as a string and validates if it is a US phone number or not?

The function should return true if the passed string is a valid US phone number.

Upvotes: 0

Views: 934

Answers (3)

Faizan Farooq
Faizan Farooq

Reputation: 320

The function should return true if the passed string is a valid US phone number.

OK. I know its project work for FreeCodeCamp javaScript challenge i would suggest reading and practicing more problems before attempting this challenge. This can be solved just by regular expression no need to loop and all that.

function telephoneCheck(str) {
  let regEx = /^(1?\s?)(\d{3}|[(]\d{3}[)])[-\s]?(\d{3})[-\s]?(\d{4})$/;
  return regEx.test(str);
}
  
telephoneCheck("555-555-5555");

Found this good article read here more about regular expressions

Upvotes: 0

Chris Barr
Chris Barr

Reputation: 34083

It depends on how "valid" you want it to be. if all you mean is that it contains exactly 10 digits, or 11 digits with the country code... then it's probably pretty simple.

function telephoneCheck(str) {
  var isValid = false;
  //only allow numbers, dashes, dots parentheses, and spaces
  if (/^[\d-()\s.]+$/ig.test(str)) {
    //replace all non-numbers with an empty string
    var justNumbers = str.replace(/\D/g, '');
    var count = justNumbers.length;
    if(count === 10 || (count === 11 && justNumbers[0] === "1") ){
      isValid = true;
    }
  }
  console.log(isValid, str);
  return isValid;
}

telephoneCheck("555-555-5555");   //true
telephoneCheck("1-555-555-5555"); //true
telephoneCheck("(555)5555555");   //true
telephoneCheck("(555) 555-5555"); //true
telephoneCheck("555 555 5555");   //true
telephoneCheck("5555555555");     //true
telephoneCheck("1 555 555 5555")  //true
telephoneCheck("2 555 555 5555")  //false (wrong country code)
telephoneCheck("800-692-7753");   //true
telephoneCheck("800.692.7753");   //true
telephoneCheck("692-7753");       //false (no area code)
telephoneCheck("");               //false (empty)
telephoneCheck("4");              //false (not enough digits)
telephoneCheck("8oo-six427676;laskdjf"); //false (just crazy)
.as-console-wrapper{max-height:100% !important;}

Upvotes: 2

Arash Motamedi
Arash Motamedi

Reputation: 10682

Google has done all humanity a huge favor and published a phone number validation and formatting library: https://github.com/googlei18n/libphonenumber

In your case, you can use the Javascript library available on NPM at https://www.npmjs.com/package/google-libphonenumber

npm install --save-prod google-libphonenumber

Then

// Get an instance of `PhoneNumberUtil`. 
const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Result from isValidNumber().
console.log(phoneUtil.isValidNumber(number));

// Result from isValidNumberForRegion().
console.log(phoneUtil.isValidNumberForRegion(number, 'US'));

Upvotes: 0

Related Questions