我们希望我们的应用程序接受rollnumbers,我们正在使用angularjs,我们无法找到一个完美的方法来验证一个必须大于0且小于某个数字的正数,如10000000
但是问题是的,我们的angularjs验证码接受1.0
这样的数字,这是我们的应用程序无法接受的,请以正确的方式进行操作
<input
type="number"
name="student_rollnumber"
class="form-control"
ng-model="student.student_rollnumber"
min="1"
max="1000000000"
required
placeholder="Student Rollnumber (required)"
step="1"
/>
答案 0 :(得分:0)
在@MatthewGreen的帮助下,在官方文档https://docs.angularjs.org/guide/forms#custom-validation
上找到答案以防他们将来更改它,我正在复制当前的工作版本:)
<form name="form" class="css-form" novalidate>
<div>
Size (integer 0 - 10):
<input type="number" ng-model="size" name="size"
min="0" max="10" integer />{{size}}<br />
<span ng-show="form.size.$error.integer">The value is not a valid integer!</span>
<span ng-show="form.size.$error.min || form.size.$error.max">
The value must be in range 0 to 10!</span>
</div>
<div>
Username:
<input type="text" ng-model="name" name="name" username />{{name}}<br />
<span ng-show="form.name.$pending.username">Checking if this name is available...</span>
<span ng-show="form.name.$error.username">This username is already taken!</span>
</div>
</form>
script.js
var app = angular.module('form-example1', []);
var INTEGER_REGEXP = /^\-?\d+$/;
app.directive('integer', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.integer = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});