首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >电话号码正则表达式-合并三个条件

电话号码正则表达式-合并三个条件
EN

Stack Overflow用户
提问于 2017-02-15 00:25:53
回答 4查看 157关注 0票数 2

我需要创建一个regex函数,它将根据特定条件验证电话号码字段,并显示三种情况下的警报。

实际上,我有这3个正则表达式函数,我想将它们组合成一个单独的函数。

代码语言:javascript
运行
复制
/^3\d{9}$/; //If it starts with 3 and has another 9 numbers it's a cellphone

/^0\d{7,10}$/; //If it starts with 0 and has another 7-10 numbers it's a landline

/^(?:00|\+)/; //If it starts with 00 or a + sign, it's an international number

我试图实现的是有一个javascript函数,它将组合这三个regex函数,并在数字无效的情况下显示特定的消息。

例如,如果数字以3开头,但数字3后面的数字少于或多于9,则可能是错误的手机号码,因此我想警告用户这一点。座机也是一样。对于国际号码,我只是想让他们知道这可能是一个国际号码,因为它以双00或+号开头。

我的问题是,我不知道如何将这三个regex值组合到一个值中,这将使我能够构建一个简单而干净的javascript代码。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-02-15 00:36:00

我想这对你来说是可行的:/^(?:3\d{9}|0\d{7,10}|(?:00|\+)\d+)$/g

代码语言:javascript
运行
复制
const testPhoneNumber = number => /^(?:3\d{9}|0\d{7,10}|(?:00|\+)\d+)$/.test(number)

const numbers = [123, "+48667065144", 3111222333, "001234567", "00123456879", 6473812354, 3475456389, 7483925821]

for (const number of numbers) {
  console.log(`${number} is ${testPhoneNumber(number) ? "valid": "not valid"} phone number`)
}

票数 0
EN

Stack Overflow用户

发布于 2017-02-15 00:37:28

代码语言:javascript
运行
复制
match(/(^3\d{9}$)|(^0\d{7,10}$)|(^(?:00|\+))/)

这将捕获数组(大小为4)中的匹配数据。

位置0:匹配的数据

位置1:第一个正则表达式的匹配数据

...

票数 0
EN

Stack Overflow用户

发布于 2017-02-15 00:49:11

代码语言:javascript
运行
复制
function check(number) {
	//var number = '3123456789';
	//var number = '01234567';
	//var number = '001';

	var regexList = [
		'^3\\d{9}$', //If it starts with 3 and has another 9 numbers it's a cellphone
		'^0\\d{7,10}$', //If it starts with 0 and has another 7-10 numbers it's a landline
		'^[0]{2}|[\+]' //If it starts with 00 or a + sign, it's an international number
	];

	for (var r in regexList)
		if (number.match(new RegExp(regexList[r])))
			break;
		else
			r = null;
			
	switch (r) {
		case "0":
			alert('If it starts with 3 and has another 9 numbers it\'s a cellphone');
			break;
		case "1":
			alert('If it starts with 0 and has another 7-10 numbers it\'s a landline');
			break;
		case "2":
			alert('If it starts with 00 or a + sign, it\'s an international number');
			break;
		default:
			alert('Invalid number');
	}
}
代码语言:javascript
运行
复制
<input type="text" id="numberToCheck" />
<input type="button" onclick="check(document.getElementById('numberToCheck').value)" />

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42231252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档