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

前端 未结 2 342
挽巷
挽巷 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))
            }
    
          })       
        
        }
      }
    }
    
    

提交回复
热议问题