JavaScript中电话号码的正则表达式
我使用RegEx验证用户电话号码。我有一套电话号码验证的要求。我对正则表达式不太了解。有人能帮我提供一个匹配的reqex来满足我的需求吗。这里的验证非常简单 条件JavaScript中电话号码的正则表达式,javascript,regex,Javascript,Regex,我使用RegEx验证用户电话号码。我有一套电话号码验证的要求。我对正则表达式不太了解。有人能帮我提供一个匹配的reqex来满足我的需求吗。这里的验证非常简单 条件 1. It should allow numbers from 0-9. 2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
1. It should allow numbers from 0-9.
2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
3. It should allow - sign. (- sign is also not mandatory and can be placed anywhere)
4. It should allow empty space everywhere.
5. No dots or no other chars allowed except the above said things.
+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234
12345+86666
123alpha
正确的值
1. It should allow numbers from 0-9.
2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
3. It should allow - sign. (- sign is also not mandatory and can be placed anywhere)
4. It should allow empty space everywhere.
5. No dots or no other chars allowed except the above said things.
+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234
12345+86666
123alpha
值不正确
1. It should allow numbers from 0-9.
2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
3. It should allow - sign. (- sign is also not mandatory and can be placed anywhere)
4. It should allow empty space everywhere.
5. No dots or no other chars allowed except the above said things.
+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234
12345+86666
123alpha
谢谢根据您的样本,尝试以下方法:
^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$
它将匹配所有的正确值
说明:
演示:
只是为了帮助你建立一些概念。
下面的正则表达式将匹配您提供的前七个输入
/^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/
\+?
将匹配+
符号。其中的?
使+
符号成为可选符号。\d{2}
匹配两位数字[-]?
匹配-
或
(空格)<代码>?使-
或
(空格)的出现成为可选。\d{5}
然后匹配5位数字。^
和$
是开始和结束锚定。基于您的示例,尝试此模式
^(?:\+?\d{2}[ -]?[\d -][\d -]+)$
首先,明确验证规则,即您希望匹配哪些模式。第二,请尝试发布您到目前为止尝试过的内容,以及您面临的问题。1up解释性图表:)这是一个很好的答案,因为它直接回答了OP,同时也提供了一个清晰的解释,这对于学习正则表达式的人来说是一个很好的资源。