1

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;

    }
  }
Cpt Kitkat
  • 1,392
  • 4
  • 31
  • 50

1 Answers1

0

Got the code from stackoverflow while looking for answer.

I made a new file and pasted the below code and added the directives in app.moule.ts declarations.

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

}

and then in mat-input I used the declaration 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>
Cpt Kitkat
  • 1,392
  • 4
  • 31
  • 50
  • 1
    This is the link autor https://stackoverflow.com/questions/51428526/how-to-restrict-special-character-in-material-input – Joan Sanchez Jun 27 '19 at 22:29