用于手机号码验证的正则表达式 [英] Regex for Mobile Number Validation
问题描述
我想要一个用于手机号码验证的正则表达式.正则表达式模式应该是它必须只在开头接受 +
并且只有在国家/地区代码之后才允许使用空格(或 -
)(仅一次).国家代码后只允许有 10 位数字.国家代码应该是可选的.如果国家代码不存在,它应该只接受 10 位数字.正则表达式应防止任何无效数字,例如(例如:+91 0000000000
或 0000000000
).
I want a regex for mobile number validation. The regex pattern should be such that it must accept +
only in beginning and space(or -
) should be allowed only after country code(only once). Only 10 digit number should be allowed after the country code. The country code should be optional. If country code doesn't exist, it should accept only 10 digit number. Regex should prevent any invalid number like (eg:+91 0000000000
or 0000000000
).
正则表达式应该接受像
- +1 8087339090
- +91 8087339090
- +912 8087339090
- 8087339090
- 08087339090
- +1-8087339090
- +91-8087339090
- +912-8087339090
- +918087677876(国家代码(2 位数)+ 10 位数手机号码)
- +9108087735454(国家代码(3 位数字)+ 10 位手机号码)
正则表达式不应该接受像
- ++51 874645(双连续 +)
- +71 84364356(双连续空格)
- +91 808 75 74 678(不超过一个空格)
- +91 808-75-74-678(不超过一个 -)
- +91-846363
- 80873(少于 10 位的数字)
- 8087339090456(大于 10 位的数字)
- 0000000000(全零)
- +91 0000000(国家代码全零)
推荐答案
如果你使用下面的技巧,就能满足你的所有要求
Satisfies all your requirements if you use the trick told below
^
行首- A
+
后跟\d+
后跟或
-
可选. - 第二点是可选的.
- 负前瞻以确保
0
不会跟随. - 匹配
\d+
10 次. - 行尾.
^
start of line- A
+
followed by\d+
followed by aor
-
which are optional. - Whole point two is optional.
- Negative lookahead to make sure
0
s do not follow. - Match
\d+
10 times. - Line end.
DEMO 在演示中添加了 m
ultiline 标志以检查所有情况
DEMO Added m
ultiline flag in demo to check for all cases
附言您确实需要指定您使用的语言,以便使用 if
条件,如下所示:
P.S. You really need to specify which language you use so as to use an if
condition something like below:
// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
这篇关于用于手机号码验证的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!