2016-08-07 36 views
2

我想在接受這三個言AngularJs使用正則表達式數字表達式:經常在AngularJs

09344542525 -> 11 length integer that start with 09 

02144532363 -> 11 length integer that start with 021 

44532363 -> 8 length integer 

這裏是我的HTML

<div class="container co-operate" ng-controller="cooperationController"> 
    <form novalidate name="cooperationForm" class="signinform"> 
     <div class="form-group inner-addon right-inner-addon"> 
      <label class="form-label control-label"></label> 
      <input ng-model="restaurantInformation.tel" type="text" name="tel" id="tel" placeholder="phone number" 
       ng-pattern="mobRegEx || prePhoneRegEx || phoneRegEx" class="form-control default-input singleline-input" required /> 
      <span class="form-icon icon icon-avatar"></span> 
     </div> 
     <p ng-show="cooperationForm.tel.$error.pattern" style="color: red">Wrong number format</p> 
    </form> 
</div> 

角:

app.controller('cooperationController', function ($scope) { 
    $scope.mobRegEx = '/09[0-3][0-9]{8}/'; 
    $scope.prePhoneRegEx = '/021[0-9]{8}/'; 
    $scope.phoneRegEx = '[0-9]{8}'; 
    . 
    . 
    . 
} 

其實,當我的輸入很髒並且我測試了整數時,錯誤段落總是顯示錯誤。

任何修改正則表達式的建議?

回答

3

全部3相結合:

/^(?:0(?:21|9[0-9]))?[0-9]{8}$/ 

說明

  • ^
  • (?:的開頭相匹配.. )?是相匹配的可選的組
    • 0(?:21|9[0-9])文字021 OR ...
    • 09和其它數字
  • [0-9]{8} 8多個數字
  • $匹配字符串的結尾也是如此。

通知我添加^ and $ anchors避免匹配的子串

+0

神話般的答案,謝謝你馬里亞諾 – AFN

0

您試圖通過使用管道將它們分開使用ng-pattern中的多個正則表達式 - 這是無效的。正如答案here中所建議的那樣,您應該實施自定義指令(ng-phone-number?)或將您的多個表達式組合爲單個模式。

使用指令可能是最可維護的方法。

+0

我已經完成了我的問題。 – AFN

+0

我的答案依然存在;實現一個自定義指令,根據任何正則表達式模式測試輸入。 –

0

變種的regexp = /(+ 09 | 021 | 44532363)\ d {1,12} /克; var result = string.match(regExp); console.log(結果)