我需要创建一个正则表达式函数,该函数将根据特定条件验证电话号码字段,并显示三种情况中的每一种情况的警报。
实际上我有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函数,它将结合这三个正则表达式函数并显示某个消息,以防数字无效。
因此,例如,如果数字以3开头但在3之后的数字少于或多于9,可能是错误的手机号码,所以我想警告用户。固定电话也是如此。对于国际号码,我只想让他们知道它可能是一个国际号码,因为它以双00或+号开头。
我的问题是我不知道如何将这三个正则表达式值组合在一起,这将允许我构建一个简单而干净的JavaScript代码。
答案 0 :(得分:1)
尽管我能做到“优雅”......
var input = '00372553253';
var matches = [];
// The following is technically one line!
[
{regex: /^3\d{9}$/, type: "cellphone"},
{regex: /^0\d{7,10}$/, type: "landline"},
{regex: /^(?:00|\+)/, type: "international"}
].forEach(
function(element) {
if (element.regex.test(input))
matches.push(element.type);
}
);
alert(matches);
测试用例实际上会匹配两个正则表达式!
答案 1 :(得分:0)
我认为这对您有用:/^(?: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`)
}
答案 2 :(得分:0)
match(/(^3\d{9}$)|(^0\d{7,10}$)|(^(?:00|\+))/)
这将捕获数组中的匹配数据(大小为4)。
位置0:匹配的数据
位置1:第一个正则表达式的匹配数据
...
答案 3 :(得分:0)
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)" />
&#13;