Skip to content

Instantly share code, notes, and snippets.

@lalogrosz
Last active November 7, 2017 12:49
Show Gist options
  • Save lalogrosz/7bccde4b768f59bef91851f74a8e11a2 to your computer and use it in GitHub Desktop.
Save lalogrosz/7bccde4b768f59bef91851f74a8e11a2 to your computer and use it in GitHub Desktop.
Angular Numeric Directive Validation
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