我有一个表单,我想在angular中放一个验证,如果用户输入任何特殊字符,那么它应该显示错误。该表单有两个字段Name和Description。在name字段中,我希望使用regex进行验证,即用户不能输入除字母数字字符以外的任何字符。
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>TypeScript代码:-
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;
}
}发布于 2019-01-16 17:53:42
在寻找答案时从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>https://stackoverflow.com/questions/54199905
复制相似问题