这是我的代码,我正在尝试验证输入内容,但验证无效
<form class="form-horizontal m-t-n" role="form">
<div class="form-group">
<div class="col-sm-4">
<div class="input-group">
<h3>{{ 'Select Quantity (max 5)' | translate }}</h3>
<input type="number" name="quantity" ng-model="quantity" ng- change="setQuantity(quantity)" value="1"class="form-control" placeholder="{{ 'Quantity' | translate }}" ng-required integer >
</div>
</div>
</div>
</form><br>
Here is my setQuantity function:
$scope.setQuantity = function setQuantity( quantity ) {
$scope.quantity = quantity;
}
答案 0 :(得分:0)
您可以使用ng-form
和$valid
属性手动检查有效性。确保将name
赋予ng-form
内的每个字段,并使用frmName[fieldName]
访问控制器中的字段。
var app = angular.module('mainApp', []);
app.controller('MyController', ['$scope', function($scope) {
$scope.setQuantity = function setQuantity(quantity) {
let isValid = $scope.myFrm['quantity'].$valid;
if (quantity && isValid) {
$scope.quantity = quantity;
}
console.log(quantity, isValid);
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="mainApp">
<div ng-controller="MyController">
<ng-form class="form-horizontal m-t-n" name="myFrm">
<div class="form-group">
<div class="col-sm-4">
<div class="input-group">
<h3>{{ 'Select Quantity (max 5)' }}</h3>
<input type="number" name="quantity" ng-model="quantity" ng-change="setQuantity(quantity)" value="1" class="form-control" placeholder="{{ 'Quantity' }}" max="5" min="1" ng-required> </div>
</div>
</div>
</ng-form>
</div>
</div>
确保input
字段位于form
标记内。此外,您可以简单地使用required
html
属性,而不需要使用ng-。检查以下代码。
<form>
<input type="number" name="quantity" ng-model="quantity"
ng-change="setQuantity(quantity)" min="1" max="5" value="1"
class="form-control" placeholder="{{ 'Quantity' | translate }}"
required integer>
<br><br>
<input type="submit" value="Submit">
</form>
如果您必须使用angular-js,然后保留ng-required
,请确保将代码放入ng-app
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="">
<form>
<input type="number" name="quantity" ng-model="quantity"
ng-change="setQuantity(quantity)" min="1" max="5" value="1"
class="form-control" placeholder="{{ 'Quantity' }}"
ng-required integer>
<br><br>
<input type="submit" value="Submit">
</form>
</div>