18

I have tried to add ion-input for maxlength , max attribute but it's not working as per expectation.

<ion-input type="number" placeholder="*" maxlength="1"></ion-input>

<ion-input type="number" placeholder="*" max="1"></ion-input>

Anyone knows the solution for the same?

Thanks

Gulam Mohammed
  • 25
  • 1
  • 1
  • 9
core114
  • 5,155
  • 16
  • 92
  • 189

4 Answers4

21

According to this post: maxlength ignored for input type="number" in Chrome

Maxlength doesn't work on input type="number"

One alternative is suggested here: https://github.com/ionic-team/ionic/issues/7072 where dilhan119 suggests using type="tel"

A robust solution is to use a form validator, which will prevent form submission (and can show the user an error): https://www.joshmorony.com/advanced-forms-validation-in-ionic-2/

DavidX
  • 1,281
  • 11
  • 16
5
HTML:
    <ion-textarea [(ngModel)]=“text” (ionChange)="textareaMaxLengthValidation()"></ion-textarea>
    <ion-input type="text" [(ngModel)]=“text” (ionChange)="textareaMaxLengthValidation()"></ion-input>


    TS:
    textareaMaxLengthValidation() {
        if (text.length > 50) {
       text= text.slice(0, 50);
        }
3

I found my way out you can use below my code. great this about it is you can keep input type number so android will show keyboard of your desire

put this code in your form builder

phone: ['', [Validators.required, this.isValidNumber.bind(this)]]

in your ts file add below method

isValidNumber(fieldControl: FormControl) {
    if(this.formBuilderGroup) {
      return fieldControl.value.toString().length < 10 ? null : {
        NotEqual: true
      };
    }
  }

in above code change formBuilderGroup to whatever your form builder group name it is. change 10 to whatever you prefer length

nirmal
  • 2,143
  • 1
  • 19
  • 29
0

I stumbled accross this issue recently and I ended up using a solution similar to the one by @Karthick Chandra Sekar, only difference is I used the standard HTML keypress event instead, since ionChange lets the event go through and causes the character to actually be displayed briefly before it gets rid of. Using keypress allows to prevent the event before it actually takes effect. So, this is how it worked out for me:

Html file:

<ion-input type="number" (keypress)="limitInputLength($event)"></ion-input>

TS code:

  limitInputLength($event, maxLength=2) {
      if($event.target.value.length>=maxLength) {
          $event.preventDefault();
          return;
      }
  }
Kilian Perdomo Curbelo
  • 1,281
  • 1
  • 15
  • 31