我正在尝试阻止字符和其他键盘输入,但数字,Tab键,退格键,删除键,左箭头键,右箭头键除外
我只是尝试了下面的代码,但这可以输入几个字符,
<input type="text" matInput required name="mobileNumber" onkeypress='return ((event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 96 && event.charCode <= 105) || (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39))'>
我怎样才能正确阻止它们
以下是我的解决方案:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[myNumberOnly]'
})
export class NumberOnlyDirective {
// Allow decimal numbers. The \. is only allowed once to occur
private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = [ 'Backspace', 'Tab', 'End', 'Home' ];
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;
}
// Do not use event.keycode this is deprecated.
// See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
let current: string = this.el.nativeElement.value;
// We need this because the current value on the DOM element
// is not yet updated with the value from this event
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
我很确定你想知道这里有什么问题,因为你使用的字符代码是HTML字符代码,你肯定会使用正确的字符。这里的问题是你的onkeypress
事件为你提供了字符的ASCII码,这就是你可以在输入字段中从'a'
到'i'
的原因。
我建议的就是这样离开
onkeypress='return (event.charCode >= 48 && event.charCode <= 57)'
其他键(箭头,删除等)仍然有效。