regex - 如何使用 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;
}
}
解决方案
在寻找答案时从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>
推荐阅读
- entity-framework - 来自存储过程的实体框架输出参数。它可以很好地添加记录,但我需要返回新插入记录的 id
- c# - 如何从 ASP.NET 应用程序内部访问“Build.BuildNumber”Azure 变量?
- javascript - 不确定的复选框在没有参考的情况下做出反应
- text - 文本框中的条件文本取决于下拉框值
- scala - 如何在 Akka-HTTP 中映射两个不同的 url:一个带参数的 url 和相同的不带参数的 url?
- laravel - 1894 未捕获的 ReferenceError:vur 未在 Module../resources/js/app.js 中定义
- mysql - 如何在 MySQL 中添加行并返回其中之一
- c++ - 如何初始化描述 RGBA 颜色的结构
- typeorm - 无法使用级联关系保存实体
- javafx - JavaFX 按钮在悬停时底部增长 1 像素,如何禁用它的增长?