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

Bhrungarajni picture Bhrungarajni · Jul 13, 2017 · Viewed 46.8k times · Source

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));
}

Answer

Maulik Modi picture Maulik Modi · Jul 13, 2017

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.