Allow only number in a ion-input with type=text Ionic

Viewed 4943

I need to make the following input so it accepts only numbers:

<ion-input formControlName="quantity"></ion-input>

I know this can be achieved with type=number but I'm restricted to using the type text for other reasons. Is it possible to do so with type text? And also how could I validate a min and max amount?

5 Answers

It can be done precisely in following way:

In your .ts file:

numericOnly(event): boolean {
   let pattern = /^([0-9])$/;
   let result = pattern.test(event.key);
   return result;
}

In your .html file:

<ion-input
        class="input"
        inputmode="numeric"
        type="number"
        (keypress)="numericOnly($event)"
      >
</ion-input>

Maybe you can do the trick with a keypress event in TypeScript file and only authorize numbers … In the listener, you can preventDefault the event, stop its propoagation and return false when it's not a digit

in your component.html:

`<ion-input (ionInput)="onInput($event)" maxlength="3" ></ion-input>`

And then in your component.ts file:

onInput($event:any) {
 let theEvent = $event || window.event,
     key = theEvent.target.value,
     regex = /[0-9]+/g
 if( !regex.test(key) ) {
   let resp = $event.target.value.match(regex)
   $event.target.value = resp ? resp.join('')  : ''
 }
}

Just prune out anything that isn't a number from the value when input is detected.

In your html file

<ion-input (ionInput)="numeric($event)" formControlName="quantity"></ion-input>

In Your ts file

numeric(event){
   let patter = /^([0-9])$/;
   let val = pattern.test(event.key);
   return val;
}
Related