Angular2 input accept only number when typing, but not doing the same while doing copy paste

angular 2 only allow numbers in input
angular 7 input number only
angular 5 input number only
angular 6 only allow numbers in input
angular 6 input number only
allow only numbers in textbox angular 7
angular 6 numbers only directive
allow only numbers and decimal in textbox angular 6

I have created an input field like as shown below in Angular2 which should accept only numbers.

html

<input type="text" name="streetCode" ngModel [maxlength]="2" (keypress)="onlyNumber($event)">

typescipt

onlyNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

The above code is working fine and allows only number from keyboard, but the issue is that when I do copy paste of some alphabet character onto to the input field it is allowing alphabets.

Update 1: Actually when I say copy paste, its through mouse copy paste and not through keyboard.

Can anyone please help me on this

Update 2

Right now I have modified the code as shown below, Don't know whether this is a right approach:

  onlyNumber(evt) {
    if (evt.type === 'paste') {
      let content = evt.clipboardData.getData('Text');
      if (isNaN(content)) {
        evt.preventDefault();
      }
    }
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      evt.preventDefault();
    }
  }

HTML

<input type="text" name="streetCode" ngModel [maxlength]="2" (keypress)="onlyNumber($event)" (paste)="onlyNumber($event)">

Why don't you use type="number" instead of text. In that case you don't need the keypress event. It is a pure html syntax.

Angular2 - Input Field To Accept Only Numbers, and you need to write the directive name in your input as an attribute I would like to build on the answer given by @omeralper , which in my opinion does not guarantee that the keyCode pertaining to the key being pressed by the user Note that in my solution i'm excluding cut, copy and paste functionality since it open  Using angular2, how can I use the same input control and apply some sort of filter/mask on this field, such that it accepts only numbers? What are the different ways I can achieve this? Note: I need to achieve this using only textbox and not using input number type.

In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

So I guess the suggestion is to use keydown/keyup events instead of keypress if you want to also listen paste event if you don't want to use type="number" instead of text.

Digit Only Directive in Angular, All these numbers are critical to identify domain models and ensure data integrity. digitOnly that we are using to make input boxes only accept digits. making users go back and fix the input is not a good experience. The goal of this directive is to discard non-digit keystrokes when users are typing and  In browsers where HTML5 constraint validation is (partially) implemented, an invalid number entered into an input[type=number] (for example) input element would be visible to the script context as the empty string.

Your function onlyNumber will get triggered only on keypress event That's the reason why it's not working on copy paste

Try using ngModelChange instead of keypress

input[number], Text input with number validation and transformation. The model must always be of type number otherwise AngularJS will throw an error. In browsers that follow the HTML5 specification, input[number] does not work as expected at the index of the last search's match, thus not taking the whole input value into account. Run as is, notice that the value in the input populates to 1 showing that initial binding is working. Change value to 2, confirm dialog will come up, hit cancel. The change function sets element = 0 but the UI will not update. Change inout to type="text" and run the same test. It works

angular.copy, Creates a deep copy of source , which should be an object or an array. This functions is used internally, mostly in the change-detection code. It is not Non-​enumerable properties (both on source and on destination ) will be ignored. angular.copy does not check if destination and source are of the same type. It's the  Problems using the maxlength attribute on text input #7393. Problems using the maxlength attribute on text input #7393. You also do same.

Angular Inputs, Angular Bootstrap inputs are special types of fields that are used in order to receive data number, password, radio, range, reset, search, submit, tel, text, and textarea. will only work when data-error and data-success attributes are not available. When doing this, be sure to add .col-form-label to your <label> s as well so  This will paste only the values (not the formulas) into the destination cells. If you want to do the same thing but copying from the cell Most people will copy the number to a new cell

Angular 5, Angular 5,6,7,8,9 - Only Number Input, Only Decimal Input. v1 Online <input numeric type="text">. Allow Numbers & Only Two Decimals [0-9] (With Decimal Limit) I would also suggest to check condition on Backspace and Delete. Copy i.e. if we put in app.module.ts file importing file and declaration of file not working. It restricts input to only numbers and decimal point in a textbox while typing. You can limit the number of digits to be allowed before and after the decimal point It also trims the digits after the decimal point if the decimal point is removed from the textbox e.g. if you have put 123.45 and then remove the decimal point it will also remove

Comments
  • Can you take a look at my Update2
  • I have seen your changes. 1. Try 'input' event <input type="text" [(ngModel)]="myValue" (change)="onlyNumber($event)" />
  • I have seen your changes.You could try something like this. 1. Try 'input' event <input type="text" name="myValue" [(ngModel)]="myValue" (input)="onlyNumber($event)" /> function onlyNumber(evt){ var value = evt.target.value; try { if(typeof value !== 'number' || isNaN(value)){ throw 'Not a number'; } value = parseFloat(value); } catch (exception) { console.error(exception); value = ''; } }
  • @fatemefazil Thanks for the reply...may be I have not conveyed my issue properly....actualy when I say copy paste....I mean through mouse copy paste...
  • @fatemefazil Can you take a look at my Update2
  • @AlexMan it's ok if it works, did you try using keydown and keyup ?
  • I have added keydown and keyup
  • you are right key up down wont trigger mouse event, your code is ok, you can write this way too: (keypress , paste)="onlyNumber($event)"
  • i checked the update but what i had in mind was <input [ngModel] ="userInputValue" (ngModelChange) ="onlyNumber($event)"/> and inside function onlyNumber have the checks for number and assign it to userInputValue
  • Can you take a look at my Update2