文本框仅接受数字

时间:2018-06-27 11:34:43

标签: angular

我必须将文本框限制为仅数字。这是我创建的指令和html。它适用于桌面浏览器,但不适用于android mobile。如何在手机上做?我正在使用angular 4和cordova插件。

html:<input type="text" fdxValidPattern="^[0-9]*$">

指令:

export class fdxValidPattern {
  @Input() fdxValidPattern: string;
  @Output() elValue = new EventEmitter<any>();
  regexStr: RegExp;
  oldVal: string = '';          

  constructor(private el: ElementRef, private zone: NgZone) { }

  @HostListener('input', ['$event']) onInput(event: Event) {
     this.regexStr = new RegExp(this.fdxValidPattern);
     // for numbers 0-9
     // this.el.nativeElement.value = (<HTMLInputElement>event.currentTarget).value.replace(/[^0-9]/g, ''); 
     // }
     // for any regex
     let newVal: string = this.el.nativeElement.value;
     let cPos = this.el.nativeElement.selectionEnd;
     if (newVal !== undefined && this.regexStr.test(newVal)) {
        this.oldVal = this.el.nativeElement.value;
     } else {
       event.stopPropagation();
       event.preventDefault();
       event.cancelBubble = true;
       this.zone.run(() => {
          this.el.nativeElement.value = this.el.nativeElement.value.replace(newVal.charAt(cPos - 1), '');
       });
    }
    if (this.el.nativeElement.value == '') {
       this.oldVal = '';
    }    
    this.elValue.emit(this.el.nativeElement.value);
  }
}

1 个答案:

答案 0 :(得分:0)

您尝试更改

<input type="text" to input type="number" />