Search code examples
ionic4angular8

Can't perform credit card formatting in angular reactive form


I am trying to perform credit card validator i.e adding space after every fourth digit like 1111 1111 1111 1111. But somehow I can't get work done.

Here is what I have tried.

Thank you in advance

html

<ion-item>
    <ion-label position="floating">Card number</ion-label>
    <ion-input  type ="tel" formControlName = "cardnumber" keypress ="cc_format($evet)" ></ion-input>
</ion-item>

ts

cc_format(value) {
    var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
    var matches = v.match(/\d{4,16}/g);
    var match = matches && matches[0] || ''
    var parts = []
    for (let i=0, len=match.length; i<len; i+=4) {
      parts.push(match.substring(i, i+4))
    }
    if (parts.length > 0) {
      return parts.join(' ')
    } else {
      return value
    }
  }

Solution

  • First let's use ionChange to get the changed value from your input. Connect your input with the creditCardNumber defined in the ts file. Now convert the credit card number and add it to the dynamic variable.

    <ion-item>
        <ion-label position="floating">Card number</ion-label>
        <ion-input  type ="tel" formControlName="cardnumber" (ionChange)="cc_format($event.target.value)" [(ngModel)]="creditCardNumber"></ion-input>
    </ion-item>
    
    creditCardNumber: string;
    
    cc_format(value: string) {
        const v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
        const matches = v.match(/\d{4,16}/g);
        const match = (matches && matches[0]) || '';
        const parts = [];
        for (let i = 0, len = match.length; i < len; i += 4) {
          parts.push(match.substring(i, i + 4));
        }
        if (parts.length > 0) {
          this.creditCardNumber = parts.join(' ');
        } else {
          this.creditCardNumber = value;
        }
      }