Angular 2 restrict input field

you need use a directive. In the directive add a hotListener about input and check if match with the regExpr indicated.
I make a directive mask some time ago. The directive in the stackblitz, with the edvertisment that the code is provide “as is” without warranty of any kind.

@Directive({
  selector: '[mask]'
})
export class MaskDirective {
  @Input()
  set mask(value) {
    this.regExpr = new RegExp(value);
  }

  private _oldvalue: string = "";
  private regExpr: any;
  private control: NgControl;
  constructor(injector: Injector) {
    //this make sure that not error if not applied to a NgControl
    try {
      this.control = injector.get(NgControl)
    }
    catch (e) {
    }
  }
  @HostListener('input', ['$event'])
  change($event) {

    let item = $event.target
    let value = item.value;
    let pos = item.selectionStart; //get the position of the cursor
    let matchvalue = value;
    let noMatch: boolean = (value && !(this.regExpr.test(matchvalue)));
    if (noMatch) {
      item.selectionStart = item.selectionEnd = pos - 1;
      if (item.value.length < this._oldvalue.length && pos == 0)
        pos = 2;
      if (this.control)
        this.control.control.setValue(this._oldvalue, { emit: false });

      item.value = this._oldvalue;
      item.selectionStart = item.selectionEnd = pos - 1; //recover the position
    }
    else
      this._oldvalue = value;
  }
}

Be carefull, when you write “mask” in a string (or in the html). e.g. for a number width two decimals is:

[mask]="'^[+-]?([1-9]\\d*|0)?(\\.\\d\{0,2\})?$'"

(the \ must be writed as \\, { as \{, } as \} …)

Leave a Comment