2016-03-31 98 views
1

我想驗證文本框只允許整數和大於零的值。AngularJs輸入文本框只允許大於零的值

這裏我附上我的代碼。

HTML:

<body ng-app="myApp"> 
    NUMBER ONLY <input type="text" allow-pattern="\d" /> 

</body> 

JS:

var app = angular.module("myApp",[]); 

app.directive('allowPattern', [allowPatternDirective]); 

function allowPatternDirective() { 
    return { 
     restrict: "A", 
     compile: function(tElement, tAttrs) { 
      return function(scope, element, attrs) { 
       element.bind("keypress", function(event) { 
        var keyCode = event.which || event.keyCode; // I safely get the 
        if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) { 
      event.preventDefault(); 
         return false; 
        }   
       }); 
      }; 
     } 
    }; 
} 

我也試過這樣的怒吼:

<body ng-app="myApp"> 
    NUMBER ONLY <input type="text" allow-pattern="^[1-9][0-9]*$" /> 

</body> 

但它不工作。

檢查的jsfiddle鏈接:click here

+0

爲什麼一個單獨的指令,你可以更好地怎麼這個過程?你可以使用'ng-pattern' –

+0

[angular validate input type =「number」](http://stackoverflow.com/questions/17395188/angular-validate-input-type-number) – Gianmarco

+0

@Gianmarco - 輸入type =「number」不適合我的情況,因爲textbox文本或數字選項基於另一個下拉選擇選項。它有可能在我的例子中做? – RSKMR

回答

0

您可以使用angular form validation,還可以使用ng-model-options

這裏是鏈接到Codepen

控制器片段:

var app = angular.module('app',[]); 
app.controller('myCtrl',function($scope){ 
$scope.onlyNumbers = /^[1-9]+[0-9]*$/; 
}) 

查看:

<div ng-app="app"> 
<br /> 
<br /> 
<div class="col-md-2" ng-controller="myCtrl"> 
    <form name="myForm1"> 
    <div class="form-group" ng-class="{'has-error':myForm1.number1.$invalid}"> 
    <label for="">Following validation happens as the user entrs a value.</label> 
    <input class="form-control" ng-pattern="onlyNumbers" ng-model="value1" name="number1"/> Valid? {{myForm1.number1.$valid}} 
    </div> 
</form> 
<form name="myForm2"> 
    <div class="form-group" ng-class="{'has-error':myForm2.number2.$invalid}"> 
    <label for="">Following validation happens after blur </label> 
    <input class="form-control" ng-pattern="onlyNumbers" ng-model="value2" name="number2" ng-model-options="{ updateOn: 'blur'}"/> Valid? {{myForm2.number2.$valid}} 
    </div> 
</form> 

更多關於通過控制器參考this link