In Angular2, how can I mask an input field(textbox) such that it accepts only numbers and not alphabets?
I have the following HTML input:
<input type="text" *ngSwitchDefault class="form-control" (change)="onInputChange()" [(ngModel)]="config.Value" focus)="handleFocus($event)" (blur)="handleBlur($event)"/>
The above input is a generic text input which may either be used as a simple text field or as a numeric field, (for example to show the Year).
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.
You can create this Validator and import it in your component.
Basically validates the form input string:
To implement it in your project:
import in your component
import { NumberValidator } from '../../validators/number.validator';
inputNumber: ['', [NumberValidator.isInteger]],
(change)="deleteCharIfInvalid()"
to the input, ifform.get('inputNumber').hasError('isInteger')
istrue
, delete the last char inserted.If you don't want a directive
https://stackblitz.com/edit/numeric-only
in component.html
in component.ts
I would like to build on the answer given by @omeralper , which in my opinion provided a good foundation for a solid solution.
What I am proposing is a simplified and up to date version with the latest web standards. It is important to note that event.keycode is removed from the web standards, and future browser updates might not support it anymore. See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
Furthermore, the method
does not guarantee that the keyCode pertaining to the key being pressed by the user maps to the expected letter as identified on the user's keyboard, since different keyboard configurations will result in a particular keycode different characters. Using this will introduce bugs which are difficult to identify, and can easily break the functionality for certain users. Rather I'm proposing the use of event.key, see docs here https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key
Furthermore, we only want that the resultant output is a valid decimal. This means that the numbers 1, 11.2, 5000.2341234 should be accepted, but the value 1.1.2 should not be accepted.
Note that in my solution i'm excluding cut, copy and paste functionality since it open windows for bugs, especially when people paste unwanted text in associated fields. That would required a cleanup process on a keyup handler; which isn't the scope of this thread.
Here is the solution i'm proposing.