如何使用 Angular 2/Typescript 限制输入字段中的特殊字符 [英] How to restrict special characters in the input field using Angular 2 / Typescript
问题描述
我是 Angular 2 的新手.我需要防止在输入字段中输入特殊字符.如果我输入字母数字,它必须接受它们,而应该阻止特殊字符.任何人都可以帮忙吗.
I am new to Angular 2. I need to prevent special characters from being typed in the input field. If I type alphanumerics, it must accept them, while special characters should be blocked. Can anyone help please.
我在这里分享代码.
在 HTML 中:
<md-input-container>
<input type="text" (ngModelChange)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
</md-input-container>
在 TS 中:
public e: any;
omit_special_char(val)
{
var k;
document.all ? k = this.e.keyCode : k = this.e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
推荐答案
你做的一切都是对的.只是功能需要稍微改动一下.您正在使用 ngModelChange 绑定不存在的事件.您可以使用 keypress 事件处理程序,如下所示.
You were doing everything right. Just the function needs to be changed a bit. You were using ngModelChange to bind event which is not there. You can use keypress event handler as shown below.
HTML
<md-input-container>
<input type="text" (keypress)="omit_special_char($event)" mdInput name="name" [(ngModel)]="company.name" placeholder="Company Name" #name="ngModel" minlength="3" required>
</md-input-container>
组件
omit_special_char(event)
{
var k;
k = event.charCode; // k = event.keyCode; (Both can be used)
return((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
"event" 是您之前传递的 "$event" 本身的对象.试试这个,它肯定会与 angular2 一起工作.
"event" is the object of "$event" itself which you have passed earlier. Try this one, it will surely work with angular2.
这篇关于如何使用 Angular 2/Typescript 限制输入字段中的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!