I've create a directive for accepting only numbers and numbers with deicmals. My code is
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[number-only]' }) export class NumberOnlyDirective { // Allow decimal numbers and negative values private regex: RegExp = new RegExp(/^-?[0-9]+(\.){0,1}([0-9]*){0,1}$/g); // Allow key codes for special events. Reflect : // Backspace, tab, end, home private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Delete"]; constructor(private el: ElementRef) { } @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) { // Allow Backspace, tab, end, and home keys 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(); } } } I'm using this directive as
<input type="number" min="0" class="form-control" number-only /> Problem is that this input element accepts two decimals like this 5..35. I've tested the regex here. It works fine.