[英]allow only numbers, TAB , DELETE, BACKSPACE, Left Arrow, Right Arrow in angular material 2 input field
I'm trying to block chars and other keyboard inputs, except Numbers , Tab Key , Backspace , Delete , Left Arrow , Right Arrow 我正在尝试阻止字符和其他键盘输入,但Numbers , Tab键 , Backspace , Delete , Left Arrow , Right Arrow除外
I just tried following code, but this can type few characters, 我刚刚尝试了以下代码,但这可以键入几个字符,
<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))'>
this is the working example 这是工作示例
How can I block those properly 我该如何正确阻止
Below is my solution: 下面是我的解决方案:
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();
}
}
}
I'm pretty sure you're wondering what's the issue here, since the char codes you're using are HTML Char Codes and you are definetly using the right ones. 我敢肯定,您想知道这里是什么问题,因为您使用的字符代码是HTML字符代码,并且您肯定使用了正确的字符代码。 The problem here is that your
onkeypress
event gives you the ASCII code of the characters, that's why you can type from 'a'
to 'i'
in your input field. 这里的问题是您的
onkeypress
事件为您提供了字符的ASCII码,这就是为什么您可以在输入字段中输入从'a'
到'i'
。
What I will suggest is to just leave it like this 我会建议就是这样离开
onkeypress='return (event.charCode >= 48 && event.charCode <= 57)'
The other keys (arrows, delete, etc..) will still work. 其他键(箭头,删除等)仍将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.