使用javascript正则表达式验证手机号码

时间:2017-10-31 10:35:05

标签: javascript regex

以下是我的代码:

<html>
<title>Validate Phone Number</title>
<head>
<script>
function testnumber() {
    var ph = new RegExp("^[789]\d{9}$");
    num = {10 digit phone number}
    alert(ph.test(num));
}
testnumber();
</script>
</head>
<body>
</body>
</html>

我想验证以7/8/9开头并且是10位数的手机号码。 但是对于作为输入的任何电话号码,它都会发出错误提示。

请告诉我哪里出错了。 提前谢谢。

3 个答案:

答案 0 :(得分:0)

试试这个,你的格式略有偏差:

function testnumber() {
    var ph = new RegExp(/^[789]\d{9}$/);
    num = 7123435498; // example number
    alert(ph.test(num));
}
testnumber();

答案 1 :(得分:0)

您现有的正则表达式并不适用于以下原因

字符串文字中的

\d评估为d

因此,您可以采取以下两种方法

1)试试这个

var ph = new RegExp("^[789]{1}[0-9]{9}$");
var num = "7894543542";
console.log( ph.test(num) ); //true
  • ^匹配字符串的开头
  • [789]匹配7,8或9
  • 中的一个
  • [0-9]{9}匹配9位
  • $匹配字符串的结尾

2)如果您传递正则表达式文字而不是字符串,那么正则表达式也能正常工作。

var ph = new RegExp(/^[789]\d{9}$/);
var num = "7894543542";
ph.test(num); //true

答案 2 :(得分:0)

您也可以尝试此HTML选项

<html>
<body>
<form action="">
 Phone number: <input type="text" pattern="[7-9]{1}[0-9]{9}" title="Enter valid number">
  <input type="submit">
</form>
</body>
</html>

相关问题