类型编号验证的输入字段不起作用

时间:2020-01-21 14:09:13

标签: angularjs validation

这是我的代码,我正在尝试验证输入内容,但验证无效

<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;
}

1 个答案:

答案 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>