关于javascript:如何在angular js中设置最大值和最小值?

How to set max and min value in angular js?

我有以下标记:

1
2
3
4
5
6
7
8
9
10
11
12
Max <span class="error">*</span>

    <!--<input style="border-right:none;" name="available_funds_max" ng-model="attributes.available_funds_max"  max="{{constants.globalValue.availablemaxNumber}}" min="{{attributes.available_funds_min}}" type="number" ng-pattern="/^[0-9]+(\\.[0-9]{1,2})?$/" step="0.01" required class="form-control input-sm m-bot15" />-->
    <input style="border-right:none;" name="available_funds_max" ng-model="attributes.available_funds_max"  ng-maxlength="15"  ng-minlength="1"  type="text" required  class="form-control input-sm m-bot15"  format="number" ng-max="{{constants.globalValue.availablemaxNumber}}" ng-min="{{attributes.available_funds_min}}"/>
    <span style="border-left:none; background:none; border-color:#e2e2e4; border-radius:0;" class="input-group-addon" id="basic-addon2">{{programname.country.currency_symbol?programname.country.currency_symbol:'$'}}</span>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.required" class="error">{{formValidation.required}}</label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.min" class="error"> {{formValidation.minMax}} </label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.max" class="error"> {{formValidation.anumberMin}} </label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.number" class="error"> {{formValidation.errorNumber}} </label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.maxlength" class="error">Max value too long</label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_max.$error.minlength" class="error">Max value too short</label>
    <label for="available_funds_max" ng-show="submittab1 && attributesForm.available_funds_min.$error.lowerThan" class="error">Value must be greater than min value</label>

我已经在 <input type="text" /> 中设置了 maxmin 的值。输入最大值或最小值后如何显示验证错误?

我想用 minmax 值验证该字段,因为我不想允许数十亿的数字,但只能达到某个最大值。如何验证输入字段并显示验证错误消息?


这是一个工作片段,只使用 ngMessages:

1
2
3
4
5
6
7
8
9
(function() {
  'use strict';

  angular.module('app', ['ngMessages'])
    .controller('mainCtrl', function($scope) {
      $scope.min = 5;
      $scope.max = 99;
    });
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.min.js">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.6.6/angular-messages.min.js">
</head>

<body ng-controller="mainCtrl">
  <form name="form">
    <label for="input">Input field:</label>
    <input type="number" name="input" min="{{min}}" max="{{max}}" ng-model="input" required step="0.01" />
   
      This field is required
      This field must be at least {{min}}.
      This field must be at max {{max}}.
      Not a valid number.
   
  </form>
</body>

</html>

Set min value. It should be numeric

1
<input type="text" ng-model="bundle.quantity" name="quantity" class="form-control text-right" placeholder="" ng-min="1" required>

If the attribute value is numeric then It will display otherwise it will remove from the DOM and make it form as invalid. Simply It will not allow the invalid values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
app.directive('ngMin', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMin, function() {
                ctrl.$setViewValue(ctrl.$viewValue);
            });
            var minValidator = function(value) {
                var min = 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);
        }
    };
});


如果你想在文本输入中设置最大值和最小值,你可以使用 ng-minlength 和 ng-maxlength。
将您的输入package在表单中,并在表单输入值上调用 $valid 以查看输入是否有效。

可以这样使用:

1
2
3
4
5
6
7
8
9
10
<form name="myForm">
    <label>
       User name:
       <input type="text" name="userName" ng-model="name" required ng-minlength="1" ng-maxlength="4">
    </label>
   
      <span class="error" ng-show="!myForm.userName.$valid">
       Required!</span>
   
</form>

仅当名称为 userName 的输入无效时才会显示跨度。
来了个小混混


我会推荐使用 Angular ngMessages 指令。然后你可以像这样将你的错误信息分组,它真的很容易使用:

1
var app = angular.module('app', ['ngMessages']);
1
2
3
div[role="alert"] {
  margin: 10px 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
<head></head>
<body ng-app="app">
  <form name="demoForm">
    <label for="myField">Text field:</label>
    <input type="text"
           name="myField"
           ng-model="field"
           ng-minlength="5"
           ng-maxlength="20"
           required />
   
      This field is required
      This field should be at least 5 characters long
      This field should be less than 20 characters long
   
    <label for="myField2">Number field:</label>
    <input type="number"
           name="myField2"
           ng-model="field2"
           ng-minlength="5"
           ng-maxlength="20"
           required />
   
      This field is required
      This field should be at least 5 characters long
      This field should be less than 20 characters long
   
  </form>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-messages.min.js">
</body>

官方文档:https://docs.angularjs.org/api/ngMessages/directive/ngMessages

根据评论编辑:

我想我现在明白你想要什么了。请参阅以下代码片段以获取答案。我为您可以设置的最小值和最大值制作了自定义指令,这些指令将验证输入。还有一个使用 ng-pattern 对输入进行模式检查,这将允许数字、逗号和点并相应地显示错误(您可以将其修改为不允许插入除数字和逗号等之外的任何内容)。请根据您的需要进行修改,但我认为这对您来说是一个很好的起点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var app = angular.module('app', ['ngMessages']);

app.directive('customMin', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            var minValidator = function (value) {
                var min = scope.$eval(attr.customMin) || 0;
                if (value) {
                \tvalue = value.replace(/[^0-9]/g, '');
                }
                console.log(value);
                if (!isEmpty(value) && value < min) {
                    ctrl.$setValidity('customMin', false);
                    return undefined;
                } else {
                    ctrl.$setValidity('customMin', true);
                    return value;
                }
            };

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

app.directive('customMax', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elem, attr, ctrl) {
            var maxValidator = function (value) {
                var max = scope.$eval(attr.customMax) || Infinity;
                if (value) {
                \tvalue = value.replace(/[^0-9]/g, '');
                }
                console.log(value);
                if (!isEmpty(value) && value > max) {
                    ctrl.$setValidity('customMax', false);
                    return undefined;
                } else {
                    ctrl.$setValidity('customMax', true);
                    return value;
                }
            };

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

function isEmpty(value) {
    return angular.isUndefined(value) || value === '' || value === null || value !== value;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
  <body>
   
      <form name="myForm">
        Value:
        <input type="text" ng-model="value" ng-pattern="/[0-9]+([\\.,][0-9]+)*/" custom-min="5" custom-max="20000" name="value" />
       
          There are some characters that are not allowed
          This field should be at least value of 5
          This field should be at most value 20,000
       
         
        <tt>value = {{value}}</tt>
       
        <tt>value.$valid = {{myForm.value.$valid}}</tt>
       
        <tt>value.$error = {{myForm.value.$error}}</tt>
      </form>
   
    <script src="https://code.angularjs.org/1.4.8/angular.min.js">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.4.8/angular-messages.min.js">
  </body>
</html>