【问题标题】:Allow only digits in input field using ionic3使用 ionic3 只允许输入字段中的数字
【发布时间】:2018-11-27 23:05:47
【问题描述】:

我有角度指令,只允许输入字段中的数字。但我尝试集成 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;
            }
          }
      }
    }

【问题讨论】:

    标签: angular validation ionic3


    【解决方案1】:

    检查一下:

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

    【讨论】:

    • @pradanya,感谢您分享您的答案。但我想完全停止键盘按下。正则表达式是另一种处理错误的方法。这对我来说很好。但我正在寻找完全停止按键(即点(。),逗号(,))
    • @vishnu,您需要使用输入而不是离子输入。像这样:
    猜你喜欢
    • 2014-09-14
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多