关于typescript:Ionic 4 ion-input仅允许输入数字,限制字母和特殊字符

Ionic 4 ion-input allow number only, restrict alphabet and special character

我正在ionic4中创建一个应用程序,我有一个功能,用户可以输入唯一的整数(0-9),因此我想限制任何其他字符,即字母,点和其他所有字符。
我试图限制使用以下指令

1
2
3
4
5
6
7
8
 @HostListener('input', ['$event']) onInputChange(event) {
    this.inputElement = this._el.nativeElement.getElementsByTagName('input')[0];
    const initalValue = this.inputElement.value;
    this.inputElement.value = initalValue.replace(/[^0-9]*/g, '');
    if (initalValue !== this.inputElement.value) {
       event.stopPropagation();
    }
}

它正在正确更新ngModel,但仍然在输入字段中显示无效字符。

我尝试了以下另一种选择

html

1
2
3
4
5
6
<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount"
        name="userCount"
        (ionInput)="countChange($event)">
 </ion-input>
 Usercount: {{userCount}}

Typescript

1
2
3
countChange(event) {
    event.target.value = event.target.value.replace(/[^0-9]*/g, '');
}

具有高于HTML的正确打印值且无无效字符,但在输入中显示无效字符。

如果我在输入中输入5,则ngModel中的值显示5,但输入字段中显示5

当我键入5,然后再次键入5时,输入字段现在显示55。

如何限制输入仅接受整数值[0-9]


您应该使用按键事件
这是例子
TS文件

1
2
3
4
5
6
7
8
9
  numberOnlyValidation(event: any) {
    const pattern = /[0-9.,]/;
    let inputChar = String.fromCharCode(event.charCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
    }
  }

HTML文件

1
2
3
4
5
<ion-input type="text" placeholder="Enter number"
        [(ngModel)]="userCount"
        name="userCount"
        (keypress)="numberOnlyValidation($event)"
 </ion-input>

它将解决您的问题。

在Ionic 5中使用指令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { Directive, HostListener } from '@angular/core';

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

  constructor() { }

  @HostListener('keypress', ['$event'])
  onInput(event: any) {
    const pattern = /[0-9]/; // without ., for integer only
    let inputChar = String.fromCharCode(event.which ? event.which : event.keyCode);

    if (!pattern.test(inputChar)) {
      // invalid character, prevent input
      event.preventDefault();
      return false;
    }
    return true;
  }

}

HTML文件

1
<ion-input appIntegerInput inputmode="numeric" type="number"></ion-input>


我按照以下步骤清除了输入字母字符的问题:

  • 我用方法创建一个util类:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    export class StringUtil {
     
        /**
         * Removes all non numeric characters from string.
         * @param str string
         */
        static removeNonNumerics = (str: string) => str.replace(/\\D/g, '');

    }

  • 创建了我的指令:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import { Directive, HostListener } from '@angular/core';

    import { StringUtil } from 'src/app/shared/utils/string.util';

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

        constructor() { }

        @HostListener('input', ['$event'])
        onInput(event: any) {
            event.target.value = StringUtil.removeNonNumerics(event.target.value);
        }

    }

  • 我已经在页面模块中导入了InputIntegerDirective:
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';

    import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
    import { IonicModule } from '@ionic/angular';

    import { DeliveryTimePageRoutingModule } from './delivery-time-routing.module';

    import { DirectivesModule } from 'src/app/shared/directives/directives.module';
    import { UiModule } from 'src/app/shared/ui/ui.module';
    import { DeliveryTimePage } from './delivery-time.page';

    @NgModule({
        imports: [
            CommonModule,
            DirectivesModule,
            FontAwesomeModule,
            FormsModule,
            IonicModule,
            DeliveryTimePageRoutingModule,
            ReactiveFormsModule,
            UiModule
        ],
        declarations: [DeliveryTimePage]
    })
    export class DeliveryTimePageModule { }

  • 最后在页面上使用它:
  • 1
    2
    <ion-input type="text" inputmode="numeric" formControlName="deliveryTime" maxlength="3" placeholder="Tempo de Entrega" [required]="true" appInputInteger>
    </ion-input>

    此指令在Web浏览器和我的移动设备上也很好。


    这是一个非常简单的解决方案。

    步骤1:创建仅数字指令,并将其放置在指令文件夹中。

    仅数字.directive.ts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    import { NgControl } from '@angular/forms';

    @Directive({
      selector: 'input[numbersOnly]'
    })
    export class NumberDirective {

      constructor(private _el: ElementRef) { }

      @HostListener('input', ['$event']) onInputChange(evt) {

        if (evt.which === 8 || evt.which === 0) {
            return true;
        }

        const regex = new RegExp("^[0-9\\~]*$");
        var key = String.fromCharCode(!evt.charCode ? evt.which : evt.charCode);
        // console.log(regex.test(key))
        if (!regex.test(key)) {
            evt.preventDefault();
            return false;
        }
        return true;
      }

    }

    **步骤2:**将其导入到app.module文件中。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import { NumberDirective } from './directive/number-only.directive';
    @NgModule({
      imports: [
        CommonModule,
      ],
      declarations: [NumberDirective],
      exports: []
    })
    export class AppModule { }

    第3步:将指令应用于如下所示的输入字段。

    1
      <input type="text" numbersOnly placeholder="Enter Mobile/Phone Number">


    这样更改代码。我希望它会解决

    1
    2
    3
    4
    countChange(event) {
       
       this.userCount += event.target.value.replace(/[^0-9]*/g, '');
    }
    1
    2
    3
    4
    5
    <ion-input type="text" placeholder="Enter number"
             name="userCount"
            (change)="countChange($event)">
     </ion-input>
     Usercount: {{userCount}}