最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set max and min value in angular js? - Stack Overflow

programmeradmin1浏览0评论

I have the following markup:

<div class="input-group-icon">Max <span class="error">*</span>
<div class="input-group">
    <!--<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> </div>
    <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>
</div>

I have set the max and min value in the <input type="text" />. How can I display a validation error when the max or min value has been entered?

I would like to validate the field with the min and max values, because I don't want to allow numbers in the billions, but only up to a certain maximum. How can I validate the input field and display a validation error message?

I have the following markup:

<div class="input-group-icon">Max <span class="error">*</span>
<div class="input-group">
    <!--<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> </div>
    <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>
</div>

I have set the max and min value in the <input type="text" />. How can I display a validation error when the max or min value has been entered?

I would like to validate the field with the min and max values, because I don't want to allow numbers in the billions, but only up to a certain maximum. How can I validate the input field and display a validation error message?

Share Improve this question edited Jul 4, 2016 at 12:12 ssc-hrep3 16.1k8 gold badges51 silver badges96 bronze badges asked Jul 4, 2016 at 10:59 Geetha JanarthananGeetha Janarthanan 612 gold badges2 silver badges6 bronze badges 4
  • 1 You can't just use "min" and "max" on "text" input. Use "number" input. – Ron Dadon Commented Jul 4, 2016 at 11:02
  • Here is the documentation with error messages: docs.angularjs/api/ng/input/input%5Btext%5D – user5524279 Commented Jul 4, 2016 at 11:03
  • But i want to check with min and max value in type="text" because am showing no in bilion number like 10,000,how to check When user enter greater than Max value and Min value show error validation? – Geetha Janarthanan Commented Jul 4, 2016 at 11:06
  • @GeethaJanarthanan, take a look at my answer: stackoverflow./questions/38183075/… – developer033 Commented Jul 4, 2016 at 13:05
Add a ment  | 

4 Answers 4

Reset to default 7

Here's a snippet working, just using ngMessages:

(function() {
  'use strict';

  angular.module('app', ['ngMessages'])
    .controller('mainCtrl', function($scope) {
      $scope.min = 5;
      $scope.max = 99;
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare./ajax/libs/angular.js/1.6.6/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare./ajax/libs/angular-messages/1.6.6/angular-messages.min.js"></script>
</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" />
    <div ng-messages="form.input.$error" style="color: #ff0000" role="alert" ng-if="form.input.$dirty">
      <div ng-message="required">This field is required</div>
      <div ng-message="min">This field must be at least {{min}}.</div>
      <div ng-message="max">This field must be at max {{max}}.</div>
      <div ng-message="number">Not a valid number.</div>
    </div>
  </form>
</body>

</html>

If you want to set the max and min value on a text input you can use ng-minlength and ng-maxlength. Wrap your inputs inside a form and call the $valid on the forms input values to see if the inputs are valid.

It can be used like this:

<form name="myForm">
    <label>
       User name:
       <input type="text" name="userName" ng-model="name" required ng-minlength="1" ng-maxlength="4">
    </label>
    <div role="alert">
      <span class="error" ng-show="!myForm.userName.$valid">
       Required!</span>
    </div>
</form>

The span will only show when the input with name userName is invalid. Here's a plunker

Set min value. It should be numeric

<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

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

I would remend using Angular ngMessages directive. Then you can group up your error messages like this and it's really easy to use:

var app = angular.module('app', ['ngMessages']);
div[role="alert"] {
  margin: 10px 0;
}
<html>
<head></head>
<body ng-app="app">
  <form name="demoForm">
    <label for="myField">Text field:</label><br>
    <input type="text"
           name="myField"
           ng-model="field"
           ng-minlength="5"
           ng-maxlength="20"
           required />
    <div ng-messages="demoForm.myField.$error" role="alert">
      <div ng-message="required">This field is required</div>
      <div ng-message="minlength">This field should be at least 5 characters long</div>
      <div ng-message="maxlength">This field should be less than 20 characters long</div>
    </div>
    <label for="myField2">Number field:</label><br>
    <input type="number"
           name="myField2"
           ng-model="field2"
           ng-minlength="5"
           ng-maxlength="20"
           required />
    <div ng-messages="demoForm.myField2.$error" role="alert">
      <div ng-message="required">This field is required</div>
      <div ng-message="minlength">This field should be at least 5 characters long</div>
      <div ng-message="maxlength">This field should be less than 20 characters long</div>
    </div>
  </form>  
  <script src="https://cdnjs.cloudflare./ajax/libs/angular.js/1.3.16/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare./ajax/libs/angular.js/1.3.16/angular-messages.min.js"></script>
</body>

Official documentation: https://docs.angularjs/api/ngMessages/directive/ngMessages

EDIT based on ments:

I think I now understood what it is that you want. Please see the following code snippet for an answer. I made custom directives for the min and max values that you can set and which will validate the input. There is also a pattern check on the input with ng-pattern which will allow numbers, mas and dots and show error accordingly (You could modify this to not allow to insert anything else than numbers and mas etc). Please modify this for your needs but I think this is a good starting point for you.

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) {
                	value = 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) {
                	value = 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;
}
<html>
  <body>
    <div ng-app="app">
      <form name="myForm">
        Value:
        <input type="text" ng-model="value" ng-pattern="/[0-9]+([\.,][0-9]+)*/" custom-min="5" custom-max="20000" name="value" />
        <div ng-messages="myForm.value.$error" role="alert">
          <div ng-message="pattern">There are some characters that are not allowed</div>
          <div ng-message="customMin">This field should be at least value of 5</div>
          <div ng-message="customMax">This field should be at most value 20,000</div>
        </div>
        <br> 
        <tt>value = {{value}}</tt>
        <br>
        <tt>value.$valid = {{myForm.value.$valid}}</tt>
        <br>
        <tt>value.$error = {{myForm.value.$error}}</tt>
      </form>
    </div>
    <script src="https://code.angularjs/1.4.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare./ajax/libs/angular-messages/1.4.8/angular-messages.min.js"></script>
  </body>
</html>

发布评论

评论列表(0)

  1. 暂无评论