Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - Input Field To Accept Only Numbers

In Angular 2, how can I mask an input field (textbox) such that it accepts only numbers and not alphabetical characters?

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 Angular 2, 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.

like image 314
Aniruddha Pondhe Avatar asked Jan 04 '17 13:01

Aniruddha Pondhe


People also ask

How do I allow only numbers in input text field?

Using <input type="number"> The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.

How do I set input to accept only numbers?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I allow only numbers in angular form field?

Allow Only Numbers in Angular Form Input For handling only numbers in the input box we simply add an input control with the ( keypress ) event handler to call the keyPressNumbers() . Below is the code snippet for this along with the output. You clearly see that only numbers are present in the input box.


2 Answers

You can use angular2 directives. Plunkr

import { Directive, ElementRef, HostListener, Input } from '@angular/core';  @Directive({   selector: '[OnlyNumber]' }) export class OnlyNumber {    constructor(private el: ElementRef) { }    @Input() OnlyNumber: boolean;    @HostListener('keydown', ['$event']) onKeyDown(event) {     let e = <KeyboardEvent> event;     if (this.OnlyNumber) {       if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||         // Allow: Ctrl+A         (e.keyCode === 65 && (e.ctrlKey || e.metaKey)) ||         // Allow: Ctrl+C         (e.keyCode === 67 && (e.ctrlKey || e.metaKey)) ||         // Allow: Ctrl+V         (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) ||         // Allow: Ctrl+X         (e.keyCode === 88 && (e.ctrlKey || e.metaKey)) ||         // Allow: home, end, left, right         (e.keyCode >= 35 && e.keyCode <= 39)) {           // let it happen, don't do anything           return;         }         // Ensure that it is a number and stop the keypress         if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {             e.preventDefault();         }       }   } } 

and you need to write the directive name in your input as an attribute

<input OnlyNumber="true" /> 

don't forget to write your directive in declarations array of your module.

By using regex you would still need functional keys

export class OnlyNumber {    regexStr = '^[0-9]*$';   constructor(private el: ElementRef) { }    @Input() OnlyNumber: boolean;    @HostListener('keydown', ['$event']) onKeyDown(event) {     let e = <KeyboardEvent> event;     if (this.OnlyNumber) {         if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||         // Allow: Ctrl+A         (e.keyCode == 65 && e.ctrlKey === true) ||         // Allow: Ctrl+C         (e.keyCode == 67 && e.ctrlKey === true) ||         // Allow: Ctrl+V         (e.keyCode == 86 && e.ctrlKey === true) ||         // Allow: Ctrl+X         (e.keyCode == 88 && e.ctrlKey === true) ||         // Allow: home, end, left, right         (e.keyCode >= 35 && e.keyCode <= 39)) {           // let it happen, don't do anything           return;         }       let ch = String.fromCharCode(e.keyCode);       let regEx =  new RegExp(this.regexStr);           if(regEx.test(ch))         return;       else          e.preventDefault();       }   } } 
like image 128
omeralper Avatar answered Oct 09 '22 09:10

omeralper


If you don't want a directive

https://stackblitz.com/edit/numeric-only

in component.html

<input (keypress)="numberOnly($event)" type="text"> 

in component.ts

export class AppComponent {    numberOnly(event): boolean {     const charCode = (event.which) ? event.which : event.keyCode;     if (charCode > 31 && (charCode < 48 || charCode > 57)) {       return false;     }     return true;    } } 
like image 20
rashidnk Avatar answered Oct 09 '22 10:10

rashidnk