3

I have a simple angular material input field

<form [formGroup]="parentFG">
  <mat-form-field>
    <input [formControlName]="CALCULATOR_INPUT" matInput placeholder="" autocomplete="off" (keyup)="updateInput($event)">
  </mat-form-field>
</form>

With a form control and validator that only allows unsigned integers

  ngOnInit() {
    let formControl = new FormControl('', UIntValidatorDirective.validateFunc);

    this.parentFG.addControl(this.CALCULATOR_INPUT, formControl);
  }

The validator works and highlights the input with red when invalid input is entered. However, I don't want to allow the user to enter invalid input in the first place. Is there a way to disallow invalid characters or strings from ever being placed in the input field?

ilooner
  • 2,480
  • 15
  • 32

1 Answers1

2

You can write a regex filter function and add desired behavior.

basic example: You can combine this with Rxjs to check the input on every keypress or a custom time interval.

    RemoveInvalidString(formInputValue){

        if (!(/^\d+$/.test(formInputValue))) { //unsigned integer?

            console.log("removing input value", formInputValue)

            formInputValue = ''

        }

    }

related posts: How to restrict special characters in the input field using angular2/ typescript

KB_
  • 2,113
  • 2
  • 26
  • 28