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

时间:2012-09-27 14:59:40

标签: javascript regex

我正在尝试使用正则表达式创建一个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 个答案:

答案 0 :(得分:3)

这应该有效。 -字符需要转义。

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

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

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

答案 1 :(得分: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;
}