簡體   English   中英

AngularJS驗證表單數組長度

[英]AngularJS validate form array length

假設我有一個帶有屬性favoriteColors的模型對象

{
    ...
    favoriteColors: ['red', 'green', 'blue']
    ....
}

我用ng-repeat將它們暴露給用戶

<form name="userForm">
    ...
    <ul>
        <li ng-repeat="color in user.favoriteColors">
            <input type="text" ng-model="color" />
            <a href="" ng-click="delete(color)">remove</a>
        </li>
    </ul>
    <a href="" ng-click="add()">Add a new favorite color</a>
    ...
</form>

我希望能夠檢查favoriteColors字段的有效性

<div ng-show="userForm.favoriteColors.$error">
    You must have at least one favorite color
</div>

這似乎並不可能做到這一點使用內置的驗證,我不知道哪個元素我把一個自定義的指令,以獲得ngModelControllerfavoriteColors

我的解決方案是添加一個隱藏的輸入標記和綁定數組的長度

    <form name="userForm">
      ...
      <ul>
        <li ng-repeat="color in user.favoriteColors">
          <input type="text" ng-model="color" />
          <a href="" ng-click="delete(color)">remove</a>
        </li>
      </ul>
      <a href="" ng-click="add()">Add a new favorite color</a>
      ...

      <!-- new line -->
      <input style="display:none" name="colorsLength" type="number" min=1 value="{{user.favoriteColors.length}}"/>
    </form>

因此,您可以使用userForm.colorsLength。$ error進行驗證。 祝好運!

@Loi Pham,遺憾的是我不允許發表評論,所以我必須添加帖子。 我喜歡你的方法。 但是我必須在輸入中添加ng-model以使驗證工作:

<input style="display: none" type="number" name="length" readonly ng-model="colors.length" min="1">

通過添加指令還有另一種方法:

/**
 * Validator for checking an array length.
 * @example
 *   <input ng-model="user.favoriteColors" validate-length />
 */
app.directive('validateLength', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {

      // do not set invalid model to undefined, should stay []
      ngModel.$options = {
        allowInvalid: true
      };

      scope.$watch(function () { return ngModel.$modelValue && ngModel.$modelValue.length; }, function() {
        ngModel.$validate(); // validate again when array changes
      });

      ngModel.$validators.length = function() {
        var arr = ngModel.$modelValue;
        if(!arr) { return false; }

        return arr.length > 0;
      };

    }
  };
});

要按照您的請求進行驗證,您必須使用ng-model將顏色數組放入表單中,以便驗證數組。

這是一個plunker的快速示例,我在ngModelController的$ parsers管道上推送一個驗證器,它將檢查顏色數組的長度。 將colorRequired指令保持獨立將允許您具有不需要顏色的情況。 您還可以添加到該指令,因此它將在屬性上采用布爾參數,以便您可以在運行時決定是否需要顏色。

http://plnkr.co/edit/yFuSXxacSW811WfZqaPC

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.colors = ['red', 'blue', 'green'];
});

app.directive("colorGroup", [function() {
    "use strict";
    return {
        restrict: 'E',
        require: 'ngModel',
        template: '<ng-form name="userForm">\
               <ul>\
               <li ng-repeat="color in model">\
              <input type="text" ng-model="color" />\
              <a href="" ng-click="delete($index)">remove</a>\
              </li>\
              </ul>\
              </ng-form>',
        link: function($scope, element, attrs, ngModelCtrl)
        {
            $scope.$watch(function(){
                return ngModelCtrl.$modelValue;
            }, function(){
                $scope.model = ngModelCtrl.$viewValue;
            });

            $scope.delete = function(idx)
            {
                        ngModelCtrl.$viewValue.splice(idx, 1);
                        ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
                        $scope.model = ngModelCtrl.$viewValue;
            }
        }
    }
}]);

app.directive("colorRequired", function() {
    "use strict";
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, element, attrs, ngModelCtrl)
        {
                ngModelCtrl.$setValidity('colorrequired', (ngModelCtrl.$viewValue.length > 0));

                ngModelCtrl.$parsers.push(function(viewValue) {
                    var valid = viewValue.length > 0;
                    ngModelCtrl.$setValidity('colorrequired', valid);
                    return valid ? viewValue : undefined;
                });
            }
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM