Praveen Bomminani
Praveen Bomminani

Reputation: 43

I want to restrict input type text only Alphanumeric in Angular 9 globally

Can any one suggest me how can I add ng-pattern / directive / RegEx globally ? so that I do not want to go to each page and touch every input by adding ng-pattern or adding directive.

My application has around 200 pages , I don't want to restrict each text input with only alpha numeric.

is there any solution write common logic that will apply for whole application ? Please suggest, I am using Angular 8.

Thank you In advance.

Upvotes: 0

Views: 6110

Answers (1)

Eliseo
Eliseo

Reputation: 57939

if you make a directive with selector input is applied to all yours inputs

@Directive({
  selector: 'input'
})

You can use a directive like this SO you are next to get it, only replace the input set mask for something like

  @Input()
  set mask(value) {
    if (value == "*")
      this.notApplied = true;
    else
      this.regExpr = new RegExp(value);
  }

declare regExpr as

  private regExpr = new RegExp(/^[A-Z|a-z|0-9]+$/);

and change the host listener checkin if this.notApplied

  @HostListener('input', ['$event'])
  change($event) {
    if (this.notApplied)
      return;
    ...
  }

All your inputs that has no [mask]="what ever" applied the mask by defect

A input with mask="*" will be a "normal" input

See the forked directive

Upvotes: 4

Related Questions