使用ionic3仅允许输入字段中的数字

时间:2018-06-19 04:32:54

标签: angular validation ionic3

我有angular指令只允许输入字段中的数字。但我尝试整合ionic3, event.preventDefault()无效。

任何人都可以建议只允许数字的方法。

<ion-input OnlyNumber="true" formControlName="oldpass" type="tel" maxlength="6">

指令:

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

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

      constructor(private el: ElementRef) { }

      @Input() OnlyNumber: boolean;

      @HostListener('keydown', ['$event']) onKeyDown(event) {
        let e = <KeyboardEvent> event;
        if (this.OnlyNumber) {
          if ([46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1) {
              return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
                //e.stopPropagation();
                //e.stopImmediatePropagation();
                //return false;
            }
          }
      }
    }

1 个答案:

答案 0 :(得分:0)

检查:

<ion-input formControlName="oldpass" type="text" maxlength="6" pattern="^-?[0-9]*[.]?[0-9]+$">