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.
I saw a lot of comments about handling copy/pasting.
To piggy back off of @omeralper answer, you can add a paste event handler to the onlyNumber directive to handle copy/pasting:
This will only allow content to be copy and pasted into the textbox ONLY if it is a number. That's the simplest solution. Changing the content of the clipboard to remove non-numerics is a lot more complicated and might not be worth it.
To get pasted text from IE you can use the following:
Use
pattern
attribute for input like below:from @omeralper 's answer. I change a little bit that won't accept period ascii (keycode 110,190). and use let ch = (e.key); to compare with regular expression when you change language (such as Thai or Japanese language) it won't accept character of those language
hope this help :)
Pattern for the Valid Mobile number pattern('^((\+91-?)|0)?[0-9]{10}$')
Pattern for accept only number from text box pattern('[0-9]*')
patter for accept only number with specific number e.g: Pincode. pattern('^[0-9]{5}$')
With support for sanitizing pasted content:
I know this is an old question, but since this is a common funcionality, I want to share the modifications I've made:
Replace strings like ".33" and "33." for the correct versions: 0.33 and 33.0
Usage: