2017-01-22 30 views
0

我正在寫一個角度指令,它只允許用戶在範圍內的輸入字段中輸入數字。不允許兩個或更多零的正則表達式在自定義角度指令的開始

HTML代碼

<input non-negative-number range-min="1" range-max="5000" ng-model="number1"> 
    <input non-negative-number range-min="0" range-max="1000" ng-model="number2"> 

角指令

angular.module("NumberDirective", []) 
    .directive('nonNegativeNumber', function() { 
    return { 
     restrict: 'A', 
     require: '?ngModel', 

     link: function (scope, element, attrs, ngModel) { 
      var lastVal = null; 
      if (!ngModel) { return; } 

      ngModel.$parsers.push(function(val) { 

       lastVal = ngModel.$modelValue; 
       var pattern = /[^0-9]+/g; 
       var parsed = val.replace(pattern, ''); 
       if (parseInt(parsed) > parseInt(attrs.rangeMax)) { parsed = lastVal; } 
       if (parseInt(parsed) < parseInt(attrs.rangeMin)) { parsed = lastVal; } 
       if (val !== parsed) { 
        lastVal = parsed; 
        ngModel.$setViewValue(parsed); 
        ngModel.$render(); 
       } 
       return parsed; 
      }); 

      element.bind('keypress', function(event) { 
       if(event.keyCode === 32) { 
        event.preventDefault(); 
       } 
      }); 
     } 
    }; 
    }); 

這是工作正常,但我也需要有正則表達式,必須不能讓打字兩個零的在輸入的開始,

like 00,0000000000045,00000000000000000000000100

任何人都可以提出正確的正則表達式?

回答

0

嘗試

^[0]{0,1}[1-9]\d{0,} 

^ asserts position at start of the string 
Match a single character present in the list below [0]{0,1} 
{0,1} Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy) 
0 matches the character 0 literally (case sensitive) 

Match a single character present in the list below [1-9] 
1-9 a single character in the range between 1 (ASCII 49) and 9 (ASCII 57) (case sensitive) 

\d{0,} matches a digit (equal to [0-9]) 
{0,} Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) 

Global pattern flags 
g modifier: global. All matches (don't return after first match) 
+0

謝謝,我使用這樣 變種圖案=/^ [0] {0,1} [1-9] \ d + /; 但它仍然允許儘可能多的0,因爲我想這是錯誤的在我的情況下 – zubairm

+0

你想允許一個零和不超過一個。如果我錯了,請糾正我。 – fossil

+0

我想用戶應該只能在01,02等數字的開始處輸入一個零,但不能爲001,00000001. 有效輸入: 1,0.01,099,99等 無效輸入: 001,0001 ,000099等等 – zubairm

相關問題