3

I have been trying to implement Angular 5+ directive that restricts user to only enter float/integer numbers.

Following is the implementation using input mask that I got from stackoverflow but is not working properly as it allows user to enter two decimal places which is wrong. Link

import {Directive, ElementRef, Input} from '@angular/core';
import * as Inputmask from 'inputmask';


@Directive({
  selector: '[app-restrict-input]',
})
export class RestrictInputDirective {

  // map of some of the regex strings I'm using (TODO: add your own)
  private regexMap = {
    integer: '^[0-9]*$',
    float: '^[+-]?([0-9]*[.])?[0-9]+$',
    words: '([A-z]*\\s)*',
    point25: '^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$'
  };

  constructor(private el: ElementRef) {}

  @Input('app-restrict-input')
  public set defineInputType(type: string) {
    Inputmask({regex: this.regexMap[type], placeholder: ''})
      .mask(this.el.nativeElement);
  }

}

I have been trying to implement this for a week but no result. Any help would be appreciated!

Renil Babu
  • 2,118
  • 1
  • 20
  • 29

0 Answers0