Last active
October 25, 2021 14:37
-
-
Save pardamike/a86d5d7f5ed58574982e06c19a0db2cb to your computer and use it in GitHub Desktop.
Angular 6 Directive to allow only positive integers in an input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// *** NOTE: This is only allowing positive integers, adjust the regex to suit your needs | |
// Stackblitz (w/ Angular Material): https://stackblitz.com/edit/angular-8fsecv?file=app%2Fnumber-only.directive.ts | |
import { Directive, ElementRef, HostListener } from '@angular/core'; | |
@Directive({ | |
selector: '[numberOnly]' | |
}) | |
export class NumberOnlyDirective { | |
// Only want positive integers | |
private regex: RegExp = new RegExp(/^\d+$/g); | |
// Allow key codes for special events Backspace, tab, end, home | |
private specialKeys = ['Backspace', 'Tab', 'End', 'Home']; | |
constructor(private el: ElementRef) { } | |
@HostListener('keydown', ['$event']) | |
onKeyDown(event: KeyboardEvent) { | |
if (this.specialKeys.indexOf(event.key) >= -1) { | |
return; | |
} | |
let current: string = this.el.nativeElement.value; | |
let next: string = current.concat(event.key); | |
if (next && !String(next).match(this.regex)) { | |
event.preventDefault(); | |
} | |
} | |
} |
to handle scientific notation (1e6), you might want to do
/^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
‘this.specialKeys.indexOf(event.key) >= -1 ’ should be changed to '‘this.specialKeys.indexOf(event.key) > -1 ’',Otherwise, you can never enter any data.
In addition, if you want to match positive integers without zero. Your regular expression needs to be modified to 'new RegExp(/^[1-9]\d*$/g)'