我想通过JavaScript RegEx检查手机号码输入,但我在构建适当的查询时遇到了困难。我只想验证手机号码。我需要的格式是: 5(0/3/4)X XXX XXXX,包括空格。
例如,532 123 4567将有效,而532 1234567无效。458 123 4567也是无效的。
为澄清这些规则,应:
- If previous digit is 0 this digit must be (5, 6 or 7)
- If previous digit is 3 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
- If previous digit is 4 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
- If previous digit is 5 this digit can be (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
我使用的代码如下:
function isPhone(phone) {
var pattern = [PATTERN HERE];
return pattern.test(phone);
}我应该使用哪种模式进行验证?
致以问候。
发布于 2017-11-17 14:40:34
与您的确切规则相匹配的简单正则表达式如下:
^5(0[5-7]|[3-5]\d) \d{3} \d{4}$请注意,如果您正在验证用户输入,则应该允许任何可用的输入,而不需要格式化。在这种情况下,应该将空格设置为可选的:
^5(0[5-7]|[3-5]\d) ?\d{3} ?\d{4}$发布于 2017-11-17 14:44:54
这是您需要的判罚:
/^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm以下是您的功能:
function isPhone(phone) {
var pattern = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
return pattern.test(phone);
}演示:
const regex = /^5(0[5-7]|[3-5]\d)\s\d{3}\s\d{4}$/gm;
const str = `532 123 4567
509 457 5879
551 123 1478
532 1234567
458 123 4567
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
https://stackoverflow.com/questions/47353013
复制相似问题