Limit the input Field to take only numbers with range

后端 未结 2 1930
旧时难觅i
旧时难觅i 2021-01-28 07:13

I want to create a input field in html where can limit the users to enter a number only between the range -40 to 130. The user can also enter decimal values For example : -40.

2条回答
  •  旧时难觅i
    2021-01-28 07:32

    as Xartok told You can use an input of type number with the attributes min max and step but if the user is keying in the input its a bit hard from my experience. what i did was like this.

    • onkeypress is used to allow users to only key in integers with decimal only.
    • ng-blur is used to trigger changeDecimal function to do the validation/rounding up to fixed decimal places

    and from the controller side what i did was this :

    1st i parse the input to float and fix it to 1 decimal place. then i made a condition to check the range if it is within the range, the input is replaced with the new value else an alert is returned. in the else section i did a small check if the input is blank or not a number then replace with a default value (to avoid a loop of alert if the input is left blank)

    app.controller('MainCtrl', function($scope) {
    
      $scope.changeDecimal = function (){
        temp = parseFloat($scope.input1).toFixed(1);
        if (temp > -40 && temp < 130 && !isNaN(temp)){
          $scope.input1= temp;
        }else{
          alert("value out of range ");
          if (isNaN (temp) || temp == null || !angular.isDefined(temp)){
            $scope.input1=0;
          }
        }
      }
    
    });
    

    If you plan to use the input type as number what you can do is set a condition for you submit button (ng-disable). the button is disabled until the condition is met.

    here is the sample from Plunker

提交回复
热议问题