2015-05-27 31 views
0

我在模板中的以下內容:的場角的驗證是有效的,但不是必需

<div class="form-group"> 
    <label for="work_phone">Work Phone</label> 
    <input type="text" 
     class="form-control" 
     name="workPhone" 
     ng-class="{'borderRed': contactInformation.workPhone.$invalid && contactInformation.submitted}" 
     ng-model="controller.contactInformation.workPhone" 
     ng-pattern="/^\d+$/" 
     maxlength="10" 
     id="work_phone"> 

    <small class="error" 
     ng-show="contactInformation.workPhone.$invalid && !contactInformation.workPhone.$pristine && contactInformation.submitted"> 
      That's not a valid phone number (only numerics are allowed)! 
    </small> 
</div> 

條件:
如果該字段爲空/不變,形式應保持有效。
2.如果在該字段中有任何值,則應該根據ng-pattern中提供的正則表達式進行驗證。

看起來很微不足道。我知道。但對於一些愚蠢的原因,無法找到一個解決方案

回答

0

所以,如果我理解你的問題,你希望只允許NUMERICS您可以使用此指令來阻止所有其他caracters:

.directive('onlyDigits', function() { 
return { 
    require: 'ngModel', 
    restrict: 'A', 
    link: function (scope, element, attr, ctrl) { 
     function inputValue(val) { 
      if (val) { 
       var digits = val.replace(/[^0-9]/g, ''); 

       if (digits !== val) { 
        ctrl.$setViewValue(digits); 
        ctrl.$render(); 
       } 
       return parseInt(digits,10); 
      } 
      return undefined; 
     }    
     ctrl.$parsers.push(inputValue); 
    } 
}; 

});

而且指令添加到您的輸入,它的速度更快,你必須不使用NG模式:

    <input type="text" 
          class="form-control" 
          name="workPhone" 
          maxlength="10" 
          id="work_phone" onlyDigits> 
0

你目前的形式保持有效開始,因爲你檢查$pristine。當表單爲空時嘗試使用$setPristine()來重置它,因此不再獲得error類。

0

你可以改變你的正則表達式,以便它允許空字符串:

ng-pattern="/^\d*$/" 
+0

所以是它,如果NG-模式的輸入定義,這將是即使「需要」的部分被跳過有效性檢查? – beNerd

相關問題