Angular JS - How do you validate the number of digits in a number input

后端 未结 4 1585
执笔经年
执笔经年 2021-01-28 17:08

What we are looking to do is, have an input that only accepts 0 - 24 (for a time entry application).

These are the values the user should be able to enter into the inpu

相关标签:
4条回答
  • 2021-01-28 17:30

    Simply add $scope.time1 = parseInt(savedTime) to the end of your function-

    var savedTime = 0;
       $scope.onChange = function(time) {
          if (time > 23 || currentTime > 2) {
            $scope.time1 = savedTime;
          } else {
            savedTime = time;  
          };
          $scope.time1 = parseInt(savedTime);
    };
    
    0 讨论(0)
  • 2021-01-28 17:34

    Maybe you could use the [ng-maxlength="number"] directive. Set it to 2 like this:

        <div class="list list-inset">
            <label class="item item-input">
                <input id="time" type="number" placeholder="24" ng-model="$parent.time1" ng-change="onChange(time1)" ng-maxlength="2">
            </label>
            <label class="item item-input">
                <input type="tel" placeholder="24" ng-model="time2" ng-maxlength="2">
            </label>
        </div>
    
    0 讨论(0)
  • 2021-01-28 17:38

    Depends on the effect you want to achieve. You can do something like this:

    <input type="text" ng-pattern="/[0-9]{1,2}/" 
                   maxlength="2"
                   ng-model="myCtrl.title">
    

    Which will prevent the user from entering any more than 2 characters. If the characters are anything but a number, it will set the field class to ng-invalid-pattern.

    If you don't want to prevent the user from entering two characters and just want to show a validation message if they enter three or more, just remove the maxlength.

    0 讨论(0)
  • 2021-01-28 17:39

    You can change your input to match a pattern:

    <input type="number" ng-pattern="/^[0-9]{1,2}$/" ...>
    
    0 讨论(0)
提交回复
热议问题