Prevent the letter 'e' and dots from being typed in an input number

前端 未结 2 339
挽巷
挽巷 2020-12-18 00:34

I have a simple input number like this:


When trying to input anything other than a number or the letter \"e\

相关标签:
2条回答
  • 2020-12-18 01:19

    You are correct that it should be done with a directive. Simply create a directive and attach it to the input. This directive should listen for keypress and/or keydown events. Possibly paste events as well. If the char entered is an 'e' or dot -- call event.preventDefault();

    angular.module('app', [])
      .directive('yrInteger', yrInteger);
    
    function yrInteger() {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
        
          element.on('keypress', function(event) {
    
            if ( !isIntegerChar() ) 
              event.preventDefault();
            
            function isIntegerChar() {
              return /[0-9]|-/.test(
                String.fromCharCode(event.which))
            }
    
          })       
        
        }
      }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
      <input 
             type="number" 
             yr-integer
             />
    </div>

    0 讨论(0)
  • 2020-12-18 01:27

    You can simply use ng-pattern on your input

    Controller

    $scope.onlyDigits= /^\d+$/;
    

    HTML

    <input ng-pattern="onlyDigits" type="number" />
    

    This pattern use \d which is for any numeric value

    0 讨论(0)
提交回复
热议问题