0

I have created the custom directive in angular 8, and i want to allow only float number upto the decimal point 2 and in between the range 0.00 to 100.00.

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

@Directive({
  selector: '[appGst]'
})
export class GstDirective {

  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      console.log(current);
      event.preventDefault();
    }
    
  }

}

entered number is now formating the like 0.00 but i want to change code so that user will enter the numbers in between 0.00 to 100.00 only.

Freestyle09
  • 4,894
  • 8
  • 52
  • 83
  • The regExpr must be like `^([0-9](\.\d{0,2})?|[1-9][0-9](\.\d{0,2})?|100(\.0{0,2})?)$` .NOTE, if you want to take a look to https://stackoverflow.com/questions/54460923/angular-2-restrict-input-field/54462816#54462816, take account that you need use `^([0-9](\\.\\d\{0,2\})?|[1-9][0-9](\\.\\d\{0,2\})?|100(\\.0{0,2\})?)$` – Eliseo Oct 29 '20 at 11:10
  • it's allowing only integer but i want to be float value between 0.00 to 100.00 – rahul jadhav Oct 29 '20 at 12:20
  • has you check the regExpr? in https://regex101.com/ you can check all the regExpr you want – Eliseo Oct 29 '20 at 14:14

0 Answers0