简体   繁体   English

手机号码的正则表达式,在某些条件下验证电话号码

[英]Regex for mobile number, phone number validation with some conditions

I want to validate both mobile number and phone number in regex.我想在正则表达式中验证手机号码和电话号码。 So the regex should pass all the below rules所以正则表达式应该通过以下所有规则

  1. There has to be at least 5 numerical.必须至少有 5 个数字。

  2. The special characters like +,(),-, # are to be used only once +,(),-,# 等特殊字符只能使用一次

  3. open and close brackets should exist mutually ie, if an open bracket is used, It has to be closed mandatorily开括号和闭括号应该相互存在,即,如果使用开括号,则必须强制关闭

  4. Maximum numbers should be 20.最大数量应为 20。

So to make this I have added this piece of code.所以为了做到这一点,我添加了这段代码。

//validate phone
function validatePhone( phone ) {
    var regex = /^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i;
    return regex.test( phone );
}

But its not validating above all the conditions.但它并没有验证所有条件。

Update It should accept all these phone numbers更新它应该接受所有这些电话号码

(+355)250235
+91 123456789012
(+355) 250-236-236-789
(+355) 2502-3656-1236-8789
+920123456789012345987
(+355) 250235 #10

You could assert at least 5 digits and not 21 digits.您可以断言至少 5 位而不是 21 位。

Then match either the part with or without parenthesis and optionally match the part with # at the end.然后匹配带或不带括号的部分,并可选择匹配末尾带有# 的部分。

^(?=(?:[^\n\d]*\d){5})(?!(?:[^\n\d]*\d){21})(?:\(\+?\d+\)|\+?\d+) ?\d+(?:-\d+)*(?: ?#\d+)?$

Regex demo正则表达式演示

First, remove the space and - (hyphen) using the below首先,使用以下内容删除空格和 - (连字符)

 var temp =str.replace(/([\s\-])/g, ''); 

Then test it using the below reg ex然后使用下面的 reg ex 测试它

^((\(){1}(\+?\d{3}(\)){1})|(\+)?\d{3})(\d){2,17}$

Try use the below function尝试使用下面的 function

function validate (str){

 var temp =str.replace(/([\s\-])/g, '');  
  var patt = /^((\(){1}(\+?\d{3}(\)){1})|(\+)?\d{3})(\d){2,17}$/g;
  var result = patt.test(temp);
}

Check This 检查这个

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM