Reputation: 855
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?
Upvotes: 2
Views: 4258
Reputation: 627469
You may use
private regex: RegExp = /^[0-9]{1,2}([,.][0-9]{0,2})?$/;
^
Note that {0,2}
quantifier makes [0-9]
match zero, one or two digits, and thus the 2.
like values will no longer stop user from typing a number with a fractional part.
Upvotes: 2