【问题标题】: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?如何编写一个将电话号码作为字符串接收并验证它是否是美国电话号码的函数?
【发布时间】:2019-05-02 17:29:01
【问题描述】:

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

【问题讨论】:

  • 您需要什么样的帮助?看起来你有一堆工作输入,可以从中采取多种方法:你有什么具体问题?
  • (另请注意,有时人们会输入888.555.1212 等数字,因此分隔符可能不应该被视为理所当然。)

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

这取决于您希望它有多“有效”。如果您的意思是它恰好包含 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;}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这似乎更像是一个评论而不是一个答案。
    • 答案是:使用谷歌的手机库。这是对解决海报问题的库的引用。
    • 更新了有助于发帖者的相关内容。
    【解决方案3】:

    如果传递的字符串是有效的美国电话号码,该函数应返回 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");

    Found this good article read here more about regular expressions

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 2010-09-15
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 2011-05-22
      • 2011-08-16
      • 1970-01-01
      相关资源
      最近更新 更多