如何编写一个函数,以字符串形式接收电话号码并验证它是否是美国电话号码?

问题描述 投票:0回答:3

如果传递的字符串是有效的美国电话号码,该函数应返回 true。

javascript ecmascript-6 ecmascript-5
3个回答
2
投票

这取决于您希望它有多“有效”。如果您的意思是它恰好包含 10 位数字,或者包含国家/地区代码的 11 位数字...那么它可能非常简单。

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;}


0
投票

Google 为全人类提供了一个巨大的帮助,并发布了电话号码验证和格式化库:https://github.com/googlei18n/libphonenumber

就您而言,您可以使用 NPM 上提供的 Javascript 库,网址为 https://www.npmjs.com/package/google-libphonenumber

npm install --save-prod google-libphonenumber

然后

// 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'));

0
投票

如果传递的字符串是有效的美国电话号码,该函数应返回 true。

好的。我知道它的项目适用于 FreeCodeCamp javaScript 挑战,我建议在尝试此挑战之前阅读并练习更多问题。 这可以通过正则表达式来解决,不需要循环等等。

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");

发现这篇好文章,在这里阅读有关正则表达式的更多信息

© www.soinside.com 2019 - 2024. All rights reserved.