如何限制 material 输入中的特殊字符

How to restrict Special character in material input

我有一个material输入控件,我在用户输入时限制了特殊字符,但是当在任何编辑器中输入一些单词并复制和粘贴带有特殊字符的单词时,这是行不通的。

我已经写了防止特殊字符的指令,但是有没有人能提供更好的解决方案限制复制粘贴。

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>

指令:

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

重现步骤:

输入不允许的特殊字符:工作正常。 而复制粘贴机智允许特殊字符

像这样尝试:

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

}

您可以使用 Ng Knife 实用程序

  1. 导入 NgKnifeModule

    ... 
    import { NgKnifeModule } from 'ng-knife';
    ...
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        NgKnifeModule
      ],
      ...
    });
    export class AppModule { }
    
  2. 使用:

    <!-- Aphanumeric -->
    <input knifeAlphanumeric type="text">
    

以下方法在不使用 setTimeout 调用的情况下工作,这意味着在使用 时输入控件中没有闪烁特殊字符

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: ClipboardEvent) {
    this.validateFields(event);
  }

  validateFields(event: ClipboardEvent) {
    event.preventDefault();
    const pasteData = event.clipboardData.getData('text/plain').replace(/[^a-zA-Z0-9 ]/g, '');
    document.execCommand('insertHTML', false, pasteData);
  }
}