简体   繁体   English

RegEx for JavaScript中的电话号码

[英]RegEx for Phone number in JavaScript

I was using RegEx to validate user phone numbers. 我使用RegEx来验证用户电话号码。 I have set of requirements for phone number validation. 我有一套电话号码验证要求。 I dont have much idea about the RegEX. 我对RegEX不太了解。 can anyone help me to provide a matching reqex for my requirement. 任何人都可以帮我提供匹配的reqex我的要求。 Here the validation is very simple. 这里的验证非常简单。

Conditions 条件

 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.

Correct values 正确的价值观

+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234

InCorrect values InCorrect值

12345+86666
123alpha

Thanks 谢谢

Based on your samples, try this: 根据您的样品,试试这个:

^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$

It will match all the correct values. 它将匹配所有正确的值。

DESCRIPTION: 描述:

正则表达式可视化

DEMO: DEMO:

http://regexr.com?340nf http://regexr.com?340nf

Just to help you build some concepts. 只是为了帮助你构建一些概念。
The following regex would match the first seven inputs you provided. 以下正则表达式将匹配您提供的前七个输入。

/^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/

\\+? would match a + sign. 会匹配一个+号。 The ? ? in it makes the + sign optional. 在它中使+符号可选。
\\d{2} matches two digits \\d{2}匹配两位数
[- ]? matches either a - or a 匹配a -或a (space). (空间)。 ? makes the occurrence of - or 发生- (space) optional. (空格)可选。
\\d{5} then matches 5 digits. \\d{5}然后匹配5位数。
^ and $ are the start and end anchors. ^$是开始和结束锚点。

根据你的样品尝试这种模式。

^(?:\+?\d{2}[ -]?[\d -][\d -]+)$

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

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