Search code examples
javascripthtmlangularjsregexng-pattern

To validate input to be only numbers with a limit of min and max 0-10000 using ng-pattern(new to angular)?


I have two input fields to be of type numeric which allows a range of min value 0 and maximum value 10000.how would i make both the fields to allow numbers between max and minimum values no values beyond that.

I have tried with the following code please review and help

<div class='panel'>
    <span>Min: $&nbsp;</span>
    <input id="text-input-1" class="width" type="number" placeholder="USD " ng-model="vm.min" ng-pattern="/^[0-9]{1,7}$/">
    <span>Max: $&nbsp;</span>
    <input id="text-input-1" class="width" type="number" placeholder="USD " ng-model="vm.max" ng-pattern="/^[0-9]{1,7}$/">
</div>

But,As per my question i want in the user input fields only not to allow the values beyond my range.rather displaying messages


Solution

  • You can use min and max attributes of <input type="number"/> and check validity of the field.

      <input id="text-input-1" min="0" max="10000" class="width" type="number" placeholder="USD" ng-model="vm.min">
    

    or you can use ng-change to force min and max value by updating value if it is greater/smaller than min and max value, but I think first approach is better.

    html

    <input id="text-input-1" type="number" ng-model="value" ng-change="setConstraints(value)">
    

    js

      $scope.setConstraints = function(value){
        if(value > 10000){
          $scope.value = 10000;
        }
    
        if(value < 0){
          $scope.value = 0;
        }
      }
    

    Demo