Angular JS-如何验证数字输入中的位数 [英] Angular JS - How do you validate the number of digits in a number input

查看:131
本文介绍了Angular JS-如何验证数字输入中的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想要做的是,有一个仅接受0-24的输入(对于时间输入应用程序).

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
4
5
6
7
8
9
00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

当前代码如下:

HTML:

        <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)">
            </label>
            <label class="item item-input">
                <input type="tel" placeholder="24" ng-model="time2" >
            </label>
        </div>

JS/角度:

  var savedTime = 0;
   $scope.onChange = function(time) {
      if (time > 23 || currentTime > 2) {
        $scope.time1 = savedTime;
      } else {
        savedTime = time;  
      };
  };

这对于限制数字效果很好,但是并不能阻止用户输入我们不希望输入的前0个数字的数量.

This works fine for limiting the numbers, but it doesn't prevent the user from entering unlimited numbers of preceding 0s, which we don't want.

我尝试使用time.toString().length并使用它添加一些验证,但结果证明,当设置为字符串时,00000作为数字仍然是"0".

I tried using time.toString().length and adding some validation using that, but turns out, 00000 as a number, when set to string still becomes "0".

是否有更好的方法将数字位数限制为2?

Is there a better way to limit the amount of digits to 2?

非常感谢.

推荐答案

只需在功能的末尾添加$scope.time1 = parseInt(savedTime)-

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

这篇关于Angular JS-如何验证数字输入中的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆