Last active
November 7, 2017 12:49
-
-
Save lalogrosz/7bccde4b768f59bef91851f74a8e11a2 to your computer and use it in GitHub Desktop.
Angular Numeric Directive Validation
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
import { Directive, HostListener, ElementRef } from '@angular/core'; | |
@Directive({ | |
selector: '[inputNumber]' | |
}) | |
export class InputNumberDirective { | |
constructor(private element: ElementRef) {} | |
@HostListener('keypress', ['$event']) | |
public onInput(event) { | |
const pattern = /[0-9.]/; | |
const inputChar = String.fromCharCode(event.charCode); | |
const isDeleting = event.charCode === 0; | |
const hasDot = this.element.nativeElement.value.indexOf('.') !== -1; | |
if ((!isDeleting && !pattern.test(inputChar)) || (hasDot && inputChar === '.')) { | |
// invalid character, prevent input | |
event.preventDefault(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment