[英]I'm trying to use regex to validate a telephone number in javascript
I'm trying to figure out why this doesn't work. 我试图弄清楚为什么这行不通。 I need to validate a telephone number in a form and my research show that this should work for a north American telephone number format.
我需要以某种形式验证电话号码,而我的研究表明这应该适用于北美电话号码格式。
I had /g at the end but that still didn't work...correctly formatted input is still false. 我在末尾有/ g,但是还是没用...正确格式化的输入仍然是false。
I used https://regex101.com/ and it looks like it is correct! 我使用了https://regex101.com/ ,看起来像是正确的!
<!DOCTYPE html>
<html lang="en-US">
<head>
</head>
<body>
<section>
<form>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="telephone" placeholder="Enter your Phone Number" />
</form>
</section>
let telInput = form.querySelector("[name='telephone']"),
tel = telInput.value;
//regex solution:
regex = /\([0-9]{3}\)\n[0-9]{3}-[0-9]{4}/;
if (!regex.test(tel)) {
alert("You have to use (xxx) xxx-xxxx format.");
telInput.focus();
return;
}
Your regex is very close! 您的正则表达式非常接近! Try replacing
\\n
(newline) with 尝试将
\\n
(换行符)替换为 (space literal).
(空格文字)。 Adding anchors
^$
also helps you avoid partial matches. 添加锚
^$
还可以帮助您避免部分匹配。
^\\([0-9]{3}\\) [0-9]{3}-[0-9]{4}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.