我需要创建一个regex函数,它将根据特定条件验证电话号码字段,并显示三种情况下的警报。
实际上,我有这3个正则表达式函数,我想将它们组合成一个单独的函数。
/^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代码。
发布于 2017-02-15 00:36:00
我想这对你来说是可行的:/^(?:3\d{9}|0\d{7,10}|(?:00|\+)\d+)$/g
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`)
}
发布于 2017-02-15 00:37:28
match(/(^3\d{9}$)|(^0\d{7,10}$)|(^(?:00|\+))/)这将捕获数组(大小为4)中的匹配数据。
位置0:匹配的数据
位置1:第一个正则表达式的匹配数据
...
发布于 2017-02-15 00:49:11
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');
}
}<input type="text" id="numberToCheck" />
<input type="button" onclick="check(document.getElementById('numberToCheck').value)" />
https://stackoverflow.com/questions/42231252
复制相似问题