只允许将范围内的数字输入文本框 [英] Allow only numbers in range to be entered into text box

查看:124
本文介绍了只允许将范围内的数字输入文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建仅接受特定范围内数字的输入文本指令.我尝试将值解析为整数,当然minmax无效.

I'm trying to create input text directive that'll only accept numbers within a specific range. I've tried parsing the value as an integer, of course min and max didn't work.

我不想使用input [type ="number"].
最终,我正在尝试创建无出生日期的输入文本字段. 如下图所示:

I do not want to use input[type="number"].
Ultimately, I'm trying to create a date of birth free input text field. Like the one seen below:

我已适应的指令[此刻我正尝试使用的指令]-原始指令可以在@

The directive I've adapted [which i'm trying to use at the moment] - the original can be found @ angularjs: allows only numbers to be typed into a text box

app.directive('onlyDigits', function () {
  return {
      restrict: 'A',
      require: '?ngModel',
      link: function (scope, element, attrs, modelCtrl) {
          modelCtrl.$parsers.push(function (inputValue) {
              if (inputValue == undefined) return '';
              var transformedInput = inputValue.replace(/[^0-9]/g, '');
              var theInt = parseInt(transformedInput);
              if (transformedInput !== inputValue) {
                  modelCtrl.$setViewValue(transformedInput);
                  modelCtrl.$render();
              }
              return theInt;
          });
      }
  };

解决此问题后,我希望做的是执行条件ng-show,以显示span元素错误-当用户键入的值超过31(对于日)或12(对于月) )等等.

What I hoped to do after I've solved this, is to do a conditional ng-show, to show an error for a span element - when the user has typed a value over 31 (for day) 12 (for month) and so forth.

我欢迎任何建议.

谢谢.

推荐答案

我遇到了完全相同的问题.我尝试过一切",以使其既用户友好,又不接受无效值.最后,我放弃了似乎很简单的解决方案,例如ng-pattern,在朋友@Teemu Turkia的帮助下,我们提出了integers-only指令.

I had the exact same problem. I tried "everything" to make it both user friendly and to not accept invalid values. Finally I gave up on apparently easy solutions, like ng-pattern, and with help of a friend @Teemu Turkia, we came up with integers-only directive.

它使用type="text",同时支持minmax,不接受数字以外的字符,并且不键入-(如果最小值为负,则为第一个字符).

It uses type="text", supports both min and max, do not accept chars beyond numbers and - (as a first character in case minimum is negative) to be typed.

此外,绝不会为ng-model分配无效值,例如空字符串或NaN,仅分配给定范围或null之间的值.

Also, ng-model is never assigned with invalid value such as empty string or NaN, only values between given range or null.

我知道,起初看起来很吓人;)

I know, at first it looks rather intimidating ;)

HTML

// note: uses underscore.js
<body>
  <form name="form">
    <header>DD / MM / YYYY</header>
    <section>
      <input type="text" 
             name="day" 
             ng-model="day" 
             min="1" 
             max="31" 
             integers-only>
      <input type="text" 
             name="month" 
             ng-model="month" 
             min="1" 
             max="12" 
             integers-only>
      <input type="text" 
             name="year" 
             ng-model="year" 
             min="1900" 
             max="2016" 
             integers-only> 
    </section>
    <section>
      <span ng-show="form.day.$invalid">Invalid day</span>
      <span ng-show="form.month.$invalid">Invalid month</span>
      <span ng-show="form.year.$invalid">Invalid year</span>
    </section>
  </form> 
</body>

JavaScript

/**
 * numeric input
 * <input type="text" name="name" ng-model="model" min="0" max="100" integers-only>
 */
angular.module('app', [])
.directive('integersOnly', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        min: '=',
        max: '='
    },
    link: function(scope, element, attrs, modelCtrl) {
      function isInvalid(value) {
        return (value === null || typeof value === 'undefined' || !value.length);
      }

      function replace(value) {
        if (isInvalid(value)) {
          return null;
        }

        var newValue = [];
        var chrs = value.split('');
        var allowedChars = ['0','1','2','3','4','5','6','7','8','9','-'];

        for (var index = 0; index < chrs.length; index++) {
          if (_.contains(allowedChars, chrs[index])) {
            if (index > 0 && chrs[index] === '-') {
              break;
            }
            newValue.push(chrs[index]);
          }
        }

        return newValue.join('') || null;
      }

      modelCtrl.$parsers.push(function(value) {
        var originalValue = value;

        value = replace(value);

        if (value !== originalValue) {
          modelCtrl.$setViewValue(value);
          modelCtrl.$render();
        }

        return value && isFinite(value) ? parseInt(value) : value;
      });

      modelCtrl.$formatters.push(function(value) {
        if (value === null || typeof value === 'undefined') {
          return null;
        }

        return parseInt(value);
      });
      modelCtrl.$validators.min = function(modelValue) {
        if (scope.min !== null && modelValue !== null && modelValue < scope.min) { return false; }
        return true;
      };
      modelCtrl.$validators.max = function(modelValue) {
        if (scope.max !== null && modelValue !== null && modelValue > scope.max) { return false; }
        return true;
      };
      modelCtrl.$validators.hasOnlyChar = function(modelValue) {
        if (!isInvalid(modelValue) && modelValue === '-') { return false; }
        return true;
      };
    }
  };
});

结果

此处的相关监听器 http://plnkr.co/edit/mIiKuw

这篇关于只允许将范围内的数字输入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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