Angular 8 validator for input with type number

Viewed 80

I have an input with a type number which allows by default the insert of some characters like '+' '-' '.'

HTML

   <input   type="number"
              class="form-control"
              formControlName="numberChildren"/>

TypeScript

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.createForm();
  }

  private createForm(): void {
    this.personalForm= this.formBuilder.group({
        numberChildren: [null, [Validators.required, Validators.pattern('[0-9]{2}')]],

    })
  }

I want to implement a logic which accept only numbers without '+' '-' '.'

Note: it is mandatory to use number as type of the input

1 Answers

You can register to the keypress event to ignore characters you do not want like the + character. This might also be more user friendly because there is no error message displayed, it just stops the character from being added to the input.

<input type="number"
  class="form-control"
  (keypress)="($event.charCode === 8 || $event.charCode === 0 || $event.charCode === 13) ? null : $event.charCode >= 48 && $event.charCode <= 57"
  formControlName="numberChildren"/>

The charCode is the ASCII character used. This will allow numbers as well as ENTER and BackSpace.

Related