最小/最大验证不工作,如果值是后来改 [英] min/max validations not working if values are changed later

查看:118
本文介绍了最小/最大验证不工作,如果值是后来改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有要求,其中一个领域的最小值取决于在另一个领域中给出的输入。

i have requirement where min value of one field depends on the input given in another field.

<input type="number" name="minval" class="form-control" ng-model="user.minval" 
      ng-required="true">

此输入用于验证另一个领域

this input is used to validate another field

<input type="number" name="inputval" class="form-control" ng-model="user.inputval" 
     ng-required="true" min="{{user.minval}}">

但这不是按预期工作..如果我改变MINVAL后输入没有得到重新验证。

but this is not working as expected.. if i change the "minval" later the input does not get revalidated..

我已经尝试设置从分钟JS初值为一些解决建议,但多数民众赞成也没有帮助...

i have tried setting the initial value for min from JS as was suggested in some solution but thats also not helping...

PLUNKER链接

推荐答案

使用NG-分钟/ NG-MAX指令

use ng-min/ng-max directives

app.directive('ngMin', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMin, function(){
                if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue);
            });

            var isEmpty = function (value) {
               return angular.isUndefined(value) || value === "" || value === null;
            }

            var minValidator = function(value) {
              var min = scope.$eval(attr.ngMin) || 0;
              if (!isEmpty(value) && value < min) {
                ctrl.$setValidity('ngMin', false);
                return undefined;
              } else {
                ctrl.$setValidity('ngMin', true);
                return value;
              }
            };

            ctrl.$parsers.push(minValidator);
            ctrl.$formatters.push(minValidator);
        }
    };
});

app.directive('ngMax', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMax, function(){
                if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue);
            });
            var maxValidator = function(value) {
              var max = scope.$eval(attr.ngMax) || Infinity;
              if (!isEmpty(value) && value > max) {
                ctrl.$setValidity('ngMax', false);
                return undefined;
              } else {
                ctrl.$setValidity('ngMax', true);
                return value;
              }
            };

            ctrl.$parsers.push(maxValidator);
            ctrl.$formatters.push(maxValidator);
        }
    };
});

这篇关于最小/最大验证不工作,如果值是后来改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆