首页 文章

正则表达式只有数字,短划线是可选的

提问于
浏览
1

我正在尝试用正则表达式创建一个javascript函数,这将验证一个电话号码 .

规则是:
1.仅限数字 . 2.超过10个数字 . 3.允许破折号( - )(可选) .

首先,我尝试了这个:

function validatePhone(phone) {

        var phoneReg = /[0-9]{10,}/;
        return (phoneReg.test(phone));
    }

它只适用于前两个规则,但不适用于破折号 .

然后我尝试了 var phoneReg = /[-0-9]{10,}/; 甚至 var phoneReg = [\d]+\-?[\d]+ ,但随后javascript被打破了......

有什么想法吗 ?

2 回答

  • 2

    这是我接近电话号码验证的方式:

    var validatePhone = function(phone) {
    
      // Stip everything but the digits.
      // People like to format phone numbers in all
      // sorts of ways so we shouldn't complain
      // about any of the formatting, just ensure the
      // right number of digits exist.
      phone = phone.replace(/\D/g, '');
    
      // They should have entered 10-14 digits.
      // 10 digits would be sans-country code,
      // 14 would be the longest possible country code of 4 digits.
      // Return `false` if the digit range isn't met.
      if (!phone.match(/\d{10,14}/)) return false;
    
      // If they entered 10, they have left out the country code.
      // For this example we'll assume the US code of '1'.
      if (phone.length === 10) phone = '1' + phone;
    
      // This is a valid number, return the stripped number
      // for reformatting and/or database storage.
      return phone;
    }
    
  • 3

    这应该工作 . 需要转义 - 字符 .

    var phoneReg = /[0-9-\-]{11,}/;
    

    这个潜在的问题是,即使字符串中没有10个数字,具有多个破折号的字符串也会测试为正数 . 我建议在测试前更换破折号 .

    var phoneReg = /[0-9]{11,}/;
    return (phoneReg.test(phone.replace(/\-/g, ''));
    

相关问题