简体   繁体   English

使用正则表达式验证电话号码并支持多个号码

[英]Validating phone number using regex with support for multuple numbers

I am not very experienced with regex and I need to validate phone numbers using javascript. 我对regex不太有经验,我需要使用javascript验证电话号码。 I have a textbox which need to be allowed to accept multiple phone numbers with a delimiter of ';' 我有一个文本框,需要允许该文本框以';'分隔符接受多个电话号码 and the characters that can be allowed for the phone numbers are 电话号码可以使用的字符是

  1. Numbers 号码
  2. '+' '+'
  3. '-' '-'

Could someone help me on how I can acheive this using javascript and regex/ regular expressions? 有人可以帮助我如何使用javascript和regex /正则表达式实现此目标吗?

Example: 例:

+91-9743574891;+1-570-456-2233;+66-12324576 + 91-9743574891; + 1-570-456-2233; + 66-12324576

I tried the following: 我尝试了以下方法:

^[0-9-+;]+$

Am not sure if this is correct. 不知道这是否正确。

You have placed - in wrong place so, your regex is not working. 您将-放置在错误的位置,因此您的regex无法正常工作。

Try this(your RegEx, but slightly modified): 试试这个(您的RegEx,但稍作修改):

^[0-9+;-]+$

or 要么

^[-0-9+;]+$

To include a hyphen within a character class then you must do one of the following: 要将连字符包含在字符类中,则必须执行以下操作之一:

  1. escape the hyphen and use \\- , 转义连字符并使用\\-
  2. place hyphen either at the beginning or at the end of the character class. 在字符类的开头或结尾放置连字符。

As the hyphen is used for specifying a range of characters. 由于连字符用于指定字符范围。 So, regex engine understands [0-9-+;]+ match any of the characters between 0 to 9 , 9 to + (all characters having decimal code-point 57 [char 9 ] to 43 [char + ] and it fails) and ; 所以,正则表达式引擎理解[0-9-+;]+匹配任何之间的字符的099+ (具有十进制码点中的所有字符57 [炭9 ]至43 [炭+ ]和失败)和; .

How about this ^([0-9\\-\\+]{5,15};?)+$ ^([0-9\\-\\+]{5,15};?)+$

Explanation: 说明:

^          #Match the start of the line
[0-9\-\+]  #Allow any digit or a +/- (escaped)
{5,15}     #Length restriction of between 5 and 15 (change as needed)
;?         #An optional semicolon
+          #Pattern can be repeat once or more
$          #Until the end of the line

Only as restrictive as specified could be tighter, See it working here . 只有在指定的限制范围内才可以收紧,请参阅此处的工作。

To be a bit more restrictive, you could use the following regexp: 为了更加严格,可以使用以下regexp:

/^\+[0-9]+(-[0-9]+)+(;\+[0-9]+(-[0-9]+)+)*$/

What it will match: 它会匹配什么:

+91-9743574891
+1-570-456-2233;+66-12324576

What it won't match: 不匹配的内容:

91-9743574891
+15704562233
6612324576

Your regex will match what you allow, but I would be a bit more restrictive: 您的正则表达式将与您所允许的相匹配,但我会更具限制性:

^\+?[0-9-]+(?:;\+?[0-9-]+)*$

See it here on Regexr 在Regexr上查看

That means match an optional "+" followed by a series of digits and dashes. 这意味着匹配一个可选的“ +”,后跟一系列的数字和破折号。 Then there can be any amount of additional numbers starting with a semicolon, then the same pattern than for the first number. 然后可以有任何数量的附加数字,以分号开头,然后是与第一个数字相同的模式。

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

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