我试图用angularjs创建一个HTML数字输入,只允许整数,没有小数。它适用于具有该数字的小数部分的数字,例如" 3.5",但不是只有十进制小数但后面没有数字的数字,例如" 3"
我使用的模式是"/^\d+$/"
,即
<input type="number" ng-model="price" name="price_field" ng-pattern="onlyNumbers" required>
并在控制器中
$scope.onlyNumbers = /^\d+$/;
如果我输入&#34; 3。&#34;然后验证消息不会出现。我希望它应该。
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field" ng-pattern="/^\d+$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input type="submit" value="submit"/>
</form>
</div>
&#13;
答案 0 :(得分:1)
问题在于type="number"
。
在HTML中,当type="number"
时,3.
是有效值。因此,我认为type="number"
优先于ng-pattern
正则表达式。
将类型更改为text
<input type="text" ng-model="price" name="price_field" ng-pattern="/^\d+$/" required>
答案 1 :(得分:0)
如果您需要禁止非数字输入,只需添加onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" ng-pattern="/^\d+$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input type="submit" value="submit"/>
</form>
</div>