Lorenzo Varano
Lorenzo Varano

Reputation: 411

Limit the input field to two decimals

I'm using Ionic/Angular for a hybrid app and in a form and I'm trying to limit the amount input field to max two decimals. However, the following code allows only to enter full numbers.

<ion-input ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" type="number" (keypress)="validateNumber($event)" placeholder="{{ 'Price_in_CHF' | translate }}" [(ngModel)]="productPrice"></ion-input>
validateNumber(event: any) {
    let input = String.fromCharCode(event.charCode);
    const reg = /^[0-9]+(\.[0-9]{1,2})?$/;

    if (!reg.test(input)) {
        event.preventDefault();
    }
}

Upvotes: 0

Views: 2688

Answers (2)

Gustavo Cagnin
Gustavo Cagnin

Reputation: 1

Replace your code with the following regex

reg = /^[0-9]{1,2}$/;

I hope that help you!

Upvotes: 0

Bhagwat Tupe
Bhagwat Tupe

Reputation: 1943

you can create your custom directive

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})

export class TwoDigitDecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-'];

  @Input('appTwoDigitDecimaNumber') decimal:any;

  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])

  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if(this.decimal){  
      if (this.specialKeys.indexOf(event.key) !== -1) {
        return;
      }
      let current: string = this.el.nativeElement.value;
      let next: string = current.concat(event.key);
      if (next && !String(next).match(this.regex)) {
        event.preventDefault();
      }
    }else{
      const charCode = (event.which) ? event.which : event.keyCode;
      if (charCode > 31 && (charCode < 48 || charCode > 105)) {
        event.preventDefault();
      }
      return;
    }
  }

Usage

<input type="text" [appTwoDigitDecimaNumber]="true">

I hope it will help you a lot.

Note : you can use it any number type field where you want use just add [appTwoDigitDecimaNumber]="true" if you dont want to use then add [appTwoDigitDecimaNumber]="false". Bacause i have use these directive in dynamic forms that why i have set it base on true or false. You can use it in Dynamic form also

Upvotes: 2

Related Questions