Angular JS自定义验证器因`ng-invalid-maxlength`而失败

时间:2015-01-12 13:24:07

标签: javascript angularjs validation

我编写了一个您可以在下面找到的自定义验证程序,它在输入值时工作正常,但是当某些内容已预先加载时,在编辑表单上,它会失败并显示ng-invalid-maxlengthng-valid-negative。< / p>

当我删除ba-non-negative时,一切正常。有人可以解释什么是错的吗?

用法

<input type="text" ba-non-negative ng-model="bookCreateForm.quantity" maxlength="5"/>

非否定指令

'use strict';

angular.module('booksApp')
    .directive('baNonNegative', function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {

                ngModel.$parsers.unshift(function (value) {
                    ngModel.$setValidity('negative', +value >= 0);
                    return +value;
                });

                ngModel.$formatters.unshift(function (value) {
                    ngModel.$setValidity('negative', +value >= 0);
                    return +value;
                });
            }
        };
    });

编辑 -

这是指向jsfiddle的链接 - http://jsfiddle.net/shvz9g28/1/

我正在使用angular 1.3.5

2 个答案:

答案 0 :(得分:0)

在格式化程序验证中,如果返回值小于零,则返回空字符串

ngModel.$formatters.unshift(function (value) {

    ngModel.$setValidity('negative', +value >= 0);

        if (+value < 0) return '';
              return +value;
    });

HTML:

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

    app.controller('MainCtrl', function($scope) {
      $scope.list_of_items = ['this', 'that', 'the other'];
      $scope.bookCreateForm = {};
      //$scope.bookCreateForm.quantity = -2;
    });

    app.directive('baNonNegative', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attr, ngModel) {

            ngModel.$parsers.unshift(function (value) {
                ngModel.$setValidity('negative', +value >= 0);
                return +value;
            });

            ngModel.$formatters.unshift(function (value) {
                ngModel.$setValidity('negative', +value >= 0);

                if (+value < 0) {
                    ngModel.$commitViewValue();
                    return '';
                }
                return (+value) ? +value : '';
            });
        }
    };
});

</script>



<input type="text" ba-non-negative ng-model="bookCreateForm.quantity" maxlength="5"/>

答案 1 :(得分:0)

我将值作为数字返回,angular有自己的maxlength验证器,用于检查viewValue.length <= maxlength;,它总是为数字返回false。

  ctrl.$validators.maxlength = function(modelValue, viewValue) {
    console.log(viewValue.length );
    return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength;
  };

简单检查

var a = 1;
a.length <= 5 //false