I created a directive that validates what the user enters in text field. User can enter numbers, dots and commas but not anything else.
The validator works when entering numbers, but I cannot enter commas and dots.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appInputValidator]'
})
export class InputValidatorDirective {
private regex: RegExp = new RegExp(/^[0-9]{1,2}([,.][0-9]{1,2})?$/);
// Allow key codes for special events
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
debugger
// 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've tested the regex online and it works for numbers, dots and commas but inside the app I can't enter dots or commas. What is wrong?
12., it doesn't match the regex12., which fails the regex check. Solution is either allow user to enter anything, and validate once focus leaves the input, or depending on the input, you might be able to craft a regex that allows the intermediate statesprivate regex: RegExp = /^[0-9]{1,2}([,.][0-9]{0,2})?$/;