i have an input and it only accept decimal number, i used custom numberic directive to validate and it's work with ENG keyboard, but when i change window key board to chinese or japanese, it's not working, code numberic directive below, pls help me, thanks
import { Directive, ElementRef, HostListener, Input } from "@angular/core";
@Directive({
selector: "[numeric]",
})
export class NumericDirective {
@Input("decimals") decimals: number = 0;
private check(value: string, decimals: number) {
if (decimals <= 0) {
return String(value).match(new RegExp(/^\d+$/));
} else {
var regExpString =
"^\\s*((\\d+(\\.\\d{0," +
decimals +
"})?)|((\\d*(\\.\\d{1," +
decimals +
"}))))\\s*$";
return String(value).match(new RegExp(regExpString));
}
}
private specialKeys = [
"Backspace",
"Tab",
"End",
"Home",
"ArrowLeft",
"ArrowRight",
"Delete",
];
constructor(private el: ElementRef) {}
@HostListener("keydown", ["$event"])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
const current: string = this.el.nativeElement.value;
const position = this.el.nativeElement.selectionStart;
const next: string = [
current.slice(0, position),
event.key === "Decimal" ? "." : event.key,
current.slice(position),
].join("");
if (next && !this.check(next, this.decimals)) {
event.preventDefault();
}
}
}