Skip to content Skip to sidebar Skip to footer

Angular Js - How Do You Validate The Number Of Digits In A Number Input

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 input: 0 1 2 3

Solution 1:

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

Solution 2:

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

    <div class="list list-inset">
        <labelclass="item item-input"><inputid="time"type="number"placeholder="24"ng-model="$parent.time1"ng-change="onChange(time1)"ng-maxlength="2"></label><labelclass="item item-input"><inputtype="tel"placeholder="24"ng-model="time2"ng-maxlength="2"></label></div>

Solution 3:

You can change your input to match a pattern:

<inputtype="number" ng-pattern="/^[0-9]{1,2}$/" ...>

Solution 4:

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

<inputtype="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.

Post a Comment for "Angular Js - How Do You Validate The Number Of Digits In A Number Input"