簡體   English   中英

僅允許在范圍內的數字輸入文本框

[英]Allow only numbers in range to be entered into text box

我正在嘗試創建輸入文本指令,它只接受特定范圍內的數字。 我嘗試將值解析為整數,當然minmax不起作用。

我不想使用輸入[type =“number”]。
最終,我正在嘗試創建一個免費輸入文本字段的出生日期。 如下所示:

日期的-birth.png

我已經改編的指令[我現在正在嘗試使用] - 可以找到原始的@ angularjs:只允許將數字輸入到文本框中

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(月份)時向前。

我歡迎任何建議。

謝謝。

我有同樣的問題。 我嘗試了“一切”,使其既方便用戶又不接受無效值。 最后,我放棄了顯然簡單的解決方案,比如ng-pattern ,在朋友@Teemu Turkia的幫助下,我們提出了integers-only指令。

它使用type="text" ,支持minmax ,不接受超出數字的字符和- (作為最小值為負的第一個字符)要鍵入。

此外, ng-model永遠不會被賦予無效值,例如空字符串或NaN ,只有給定范圍之間的值或null

我知道,起初它看起來相當令人生畏;)

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

結果

圖片


相關的plunker在這里http://plnkr.co/edit/mIiKuw

這是沒有任何自定義指令的解決方案。 它仍然是input type="number"但實現了所需的功能。

這里是plunker

 <!DOCTYPE html> <html> <head></head> <body ng-app="app" ng-controller="dobController as dob"> <h3>Date of birth form</h3> <form name="dobForm" class="form" novalidate=""> <div> <label for="date">DD</label> <input type="number" ng-model="dob.date" name="date" min="1" max="31" integer /> <label for="month">MM</label> <input type="number" ng-model="dob.month" name="month" min="1" max="12" integer /> <label for="year">YYYY</label> <input type="number" ng-model="dob.year" name="year" min="1900" max="2016" integer /> <div style="color: red;" ng-if="dobForm.$invalid"> <p ng-show="dobForm.date.$error.min || dobForm.date.$error.max"> date must be in range 1 to 31! </p> <p ng-show="dobForm.month.$error.min || dobForm.month.$error.max"> month must be in range 1 to 12! </p> <p ng-show="dobForm.year.$error.min || dobForm.year.$error.max"> year must be in range 1900 to 2016! </p> </div> </div> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-messages.js"></script> <script> var app = angular.module('app', []); app.controller('dobController', function($scope) {}); </script> <style> input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } </style> </body> </html> 

在此輸入圖像描述

此解決方案使用min和max屬性來限制輸入字段的值。 它還使用ngModelOptions僅在定義的時間間隔后更新模型值。 這是為了允許用戶在模型解析器作用於輸入之前鍵入值。

 angular.module("app", []); angular.module("app").directive('onlyDigits', function() { return { restrict: 'A', require: '?ngModel', scope: { min: "@", max: "@" }, 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); var max = scope.max; var min = scope.min; if (theInt > max) { theInt = max; } else if (theInt < min) { theInt = min; } modelCtrl.$setViewValue(theInt.toString()); modelCtrl.$render(); return theInt; }); } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> <body ng-app="app"> <input type="text" ng-model="month" ng-model-options="{ debounce: 200 }" only-digits min="1" max="12"> <input type="text" ng-model="day" ng-model-options="{ debounce: 200 }" min="1" max="30" only-digits> <input type="text" ng-model="year" ng-model-options="{ debounce: 500 }" only-digits min="1900" max="2050"> </body> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM