Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 ion-input allow number only, restrict alphabet and special character

I am creating an app in ionic4, I have a functionality where user can enter the only integer number (0-9), so I want to restrict any other character i.e alphabets, dot, plus everything.
I tried to restrict is using the following directive

 @HostListener('input', ['$event']) onInputChange(event) {
    this.inputElement = this._el.nativeElement.getElementsByTagName('input')[0];
    const initalValue = this.inputElement.value;
    this.inputElement.value = initalValue.replace(/[^0-9]*/g, '');
    if (initalValue !== this.inputElement.value) {
       event.stopPropagation();
    }
}

It is updating ngModel correctly but still, an invalid character is visible in the input field.

I tried another option as following

html

<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount" 
        name="userCount" 
        (ionInput)="countChange($event)">
 </ion-input>
 Usercount: {{userCount}}

Typescript

countChange(event) {
    event.target.value = event.target.value.replace(/[^0-9]*/g, '');
}

With above its printing value in HTML correct without invalid character, but its showing invalid character in input.

If I enter 5+ in input, the value in ngModel shows 5 but input field showing 5+

When I type 5++ and then type 5 again, input field shows 55 now.

How can I restrict input to accept only integer values [0-9]

like image 832
Divyesh Savaliya Avatar asked Aug 07 '19 12:08

Divyesh Savaliya


1 Answers

You should use keypress event Here is the example TS File

  numberOnlyValidation(event: any) {
    const pattern = /[0-9.,]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
  }

HTML File

<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount" 
        name="userCount" 
        (keypress)="numberOnlyValidation($event)"
 </ion-input>

It will resolve your issue.

Using directive in Ionic 5:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[appIntegerInput]'
})
export class IntegerInputDirective {

  constructor() { }

  @HostListener('keypress', ['$event'])
  onInput(event: any) {
    const pattern = /[0-9]/; // without ., for integer only
    let inputChar = String.fromCharCode(event.which ? event.which : event.keyCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
      return false;
    }
    return true;
  }

}

HTML File

<ion-input appIntegerInput inputmode="numeric" type="number"></ion-input>
like image 151
Virendra Yadav Avatar answered Oct 21 '22 13:10

Virendra Yadav