我有以下代码,可防止在浏览器应用程序中键入特殊字符。但是在移动用户中,其键盘有所不同,可以直接输入特殊字符。我该如何预防?
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appNumeric]'
})
export class NumericDirective {
constructor(private elemRef: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(event) {
const e = <KeyboardEvent>event;
const keyCode = e.charCode || e.keyCode;
const allowedKeys = [46, 8, 9, 27, 13];
if (allowedKeys.indexOf(keyCode) !== -1 ||
// Allow: Ctrl+A
(keyCode === 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(keyCode === 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(keyCode === 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(keyCode >= 35 && keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (keyCode < 48 || keyCode > 57)) && (keyCode < 96 || keyCode > 105)) {
e.preventDefault();
}
}
}