Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

html - How to restrict special characters in the input field using Angular 2 / Typescript

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.

I am sharing the code here.

In 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>

In 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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

Component

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" is the object of "$event" itself which you have passed earlier. Try this one, it will surely work with angular2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...