How to restrict Special character in material input

Mohamed Sahir picture Mohamed Sahir · Jul 19, 2018 · Viewed 15.5k times · Source

I have a material input control, i have restrict the special character while user enter, but when type some words in any editor and copy and paste the words with special character, which is not working.

I have write the directive for that to prevent special character,but can one provide the better solution restrict in copy paste.

app.component.html:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput specialIsAlphaNumeric placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>

directive:

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

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

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

}

demo see here:

https://stackblitz.com/edit/angular-cijbqy-biwrck?file=app%2Finput-overview-e[stackblit][1]

Steps to reproduce:

type it special character which is not allowed : working fine. while copy paste wit allows special character

Answer

Akj picture Akj · Jul 19, 2018

Try Like this:

stackblitz example

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

}