I have a form and I want to put a validation in angular in such a way that if a user enters any special character then it should show error. The form has two fields Name and Description. In name field I want to put validation using regex that the user should not be able to enter anything other than alphanumeric characters.
HTML Code:
<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 Code:-
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;
}
}