首页 > 解决方案 > 如何使用 RegEx 删除 Mat-Input 中的空白和特殊字符

问题描述

我有一个表单,我想以这样的方式进行角度验证,如果用户输入任何特殊字符,那么它应该显示错误。该表单有两个字段名称和说明。在名称字段中,我想使用正则表达式进行验证,即用户不应输入除字母数字字符以外的任何内容。

HTML 代码:

 <form (ngSubmit)="(submit)" #formControl="ngForm">
                    <div class="form">
                        <mat-form-field color="accent">
                            <input
                                matInput
                                #input
                                class="form-control"
                                placeholder="name"
                                [(ngModel)]="data.projectName"
                                name="name"
                                (ngModelChange)="noWhiteSpaceOnChange()"
                                required
                                minlength="4"
                            />

                            <mat-error *ngIf="formControl.invalid">{{
                                getErrorMessage()
                            }}</mat-error>
                        </mat-form-field>
                    </div>
                   </form>

打字稿代码:-

 noWhiteSpaceOnChange() {
    const validationRegex = /^((?!\s{1,}).)*$/
    if (!validationRegex.test(this.data.projectName)) {
       // this.data.projectName= '';
      let str = this.data.projectName;
      str = str.replace(/[^A-Z0-9]+/ig, "_");
      this.data.projectName=str;

    }
  }

标签: regexangulartypescriptangular-material

解决方案


在寻找答案时从stackoverflow获取代码。

我创建了一个新文件并粘贴了以下代码,并在 app.moule.ts 声明中添加了指令。

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

}

然后在 mat-input 我使用了声明specialIsAlphaNumeric

<mat-form-field color="accent">
                            <input
                                matInput specialIsAlphaNumeric
                                class="form-control"
                                placeholder="name"
                                [(ngModel)]="data.projectName"
                                name="name"
                                required
                                minlength="4"
                            />

                            <mat-error *ngIf="formControl.invalid">{{
                                getErrorMessage()
                            }}</mat-error>
                        </mat-form-field>

推荐阅读