ryy77
ryy77

Reputation: 1294

How to remove entering special characters while i'm typing? (Angular)

How can I remove special characters while I'm typing in the input field. I used (keyup) or (keydown) and replace for this. I attached the code. I will appreciate any help. Thanks!

removeSpecialCharacters(event) {
    let newVal = event.target.value.replace('[^A-Za-z0-9]', '');
    return newVal;
  }
<input maxlength="10" (keydown)="this.removeSpecialCharacters($event)">

Upvotes: 2

Views: 10757

Answers (3)

kcsujeet
kcsujeet

Reputation: 522

use data binding and (change) event listener. if you're going for a form then consider using formbuilder and using formControlName for data bindig. that's an easier approach.

Upvotes: 1

Rabea AlTaradeh
Rabea AlTaradeh

Reputation: 224

You can use this Directive

import { Directive, HostListener, ElementRef, Input } from '@angular/core';
@Directive({
  selector: '[specialIsAlphaNumeric]'
})
export class SpecialCharacterDirective {

  regexStr = '^[a-zA-Z0-9_]*$';
  @Input() isAlphaNumeric: boolean;

  constructor(private el: ElementRef) { }


  @HostListener('keypress', ['$event']) onKeyPress(event) {
    return new RegExp(this.regexStr).test(event.key);
  }

  @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
    this.validateFields(event);
  }

  validateFields(event) {
    setTimeout(() => {

      this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]/g, '').replace(/\s/g, '');
      event.preventDefault();

    }, 100)
  }

}

like <input specialIsAlphaNumeric placeholder="my love" value="Mam"> don't forget add the Directive class in declarations on ngModule

Upvotes: 5

mbojko
mbojko

Reputation: 14679

Now newVal isn't in any way connected to your input element. Try binding it using, for example, ngModel:

inputModel: string;

removeSpecialCharacters(event) {
    this.inputModel = event.target.value.replace('[^A-Za-z0-9]', '');
}
<input maxlength="10" (keydown)="this.removeSpecialCharacters($event)" [(ngModel)]="inputModel">

Upvotes: 2

Related Questions