Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

angularjs

I have a simple input number like this:

<input type="number"/>

When trying to input anything other than a number or the letter "e", it doesn't work, but when I type the letter "e" it works.

I checked w3.org specs, and it states clearly that floating numbers can be typed using the normal notation (ex : 10.2) or the scientific notation (ex : 1e2).

So my question is : Is there a way to prevent the user from typing e letters and dots. Said in another way : Is there a way to make the input number accept ONLY INTEGER NUMBERS ?

I have the idea of doing that with an Angular directive that I will input as an attribute to my input number, but I really don't know how to make that work.

EDIT : What I would like to do is to simulate the same behaviour that we have now when trying to type any other letter in the alphabet other than "e", or ".". What I want to say is that I do not want to see the letter appearing in the input (Like it is the case now).

like image 891
Mathemagician Avatar asked Jul 07 '16 09:07

Mathemagician


People also ask

How do you restrict characters in input?

To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

Why does input number allow E?

The E stands for the exponent, and it is used to shorten long numbers. Since the input is a math input and exponents are in math to shorten great numbers, so that's why there is an E.

How do you stop character input in HTML?

The typical way to prevent input of certain characters is to listen to the keydown event, check the character that is being input, then use event. preventDefault() to stop the input from occurring.


1 Answers

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>
like image 178
Martin Avatar answered Oct 16 '22 10:10

Martin