如何使用Angular 2/Typescript在输入字段中限制特殊字符 [英] How to restrict special characters in the input field using Angular 2 / Typescript

查看:201
本文介绍了如何使用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)); 
}

事件"是您先前已通过的"$事件"本身的对象.试试这个,它肯定可以与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆