2015-04-30 293 views
0

下列格式允许的电话号码angulars JS客户端验证

  1. XXX-XXX-XXXX [x表示数字]
  2. xxx.xxx.xxxx
  3. XXXXXXXXXX [数字的十倍]

我对格式工作样例,但我无法对他们在一个单一的正则表达式相结合。如何将它们合并为一个正则表达式?

  1. "/^[1-9]\d{2}-\d{3}-\d{4}|^\d{10}$/"
  2. "/^[1-9]\d{2}[.]\d{3}[.]\d{4}|^\d{10}$/"
  3. "/^\d{10}$/"

我的角度的正则表达式代码:

<div class="form-group" ng-class="{'has-error':userprofileForm.phone.$touched && userprofileForm.phone.$invalid && userprofileForm.extension.$touched && userprofileForm.extension.$invalid}"> 
    <label for="profile-phone" class="control-label">{{'PHONE'|translate }}</label> 
    <div> 
     <input name="phone" type="text" class="form-control" ng-model="userprofile.phoneNumber" ng-pattern="/^\d{10}$/" required="required" /> 
     <div ng-show="userprofileForm.phone.$touched && userprofileForm.phone.$invalid">  
      <span ng-message="required">Please enter phone number</span> 
     </div> 
    </div> 
</div> 

回答

1

你可以像这样将它们组合起来:

ng-pattern="/^([1-9]\d{2}-\d{3}-\d{4})|([1-9]\d{2}\.\d{3}\.\d{4})|(\d{10})$/" 

只要把自己的组中,每个图案()他们一起|

或者更紧凑的使用恢复参照(假设你的第三种情况应该也不能以0开始):

ng-pattern="/^[1-9]\d{2}([.-]?)\d{3}\1\d{4}$/" 

正则表达式崩溃:

^  // start of line 
[1-9] // match '1', '2', '3', '4', '5', '6', '7', '8' or '9' 
\d{2) // match 2 digits 
(  // begin capturing group 1 
[.-] // match '.' or '-' 
?  // make the preceeding [.-] optional, so capturing group 1 matches '.', '-' or nothing. 
)  // end capturing group 1 
\d{3) // match 3 digits 
\1  // back reference: match what was matched by capturing group 1 
\d{4) // match 4 digits 
$  // match end of line 

注意的是,由于使用后面的引用混合像xxx.xxx-xxxx被正确拒绝。

+0

''[1-9]'不是'\ d'。 +1使用反向引用。 – zeroflagL

+0

@zeroflagL:谢谢你的收获!答案已更新。 – TijsH

+0

catch =“/^[1-9] \ d {2}([.-]?)\ d {3} \ 1 \ d {4} $ /”使这个组合有效xxx.xxx-xxxx,它不应该是这样的。 – arvind