【问题标题】:Ionic 4 ion-input allow number only, restrict alphabet and special characterIonic 4 离子输入只允许数字,限制字母和特殊字符
【发布时间】:2019-12-15 01:58:08
【问题描述】:

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

 @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

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

打字稿

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

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

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

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

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

【问题讨论】:

  • 嘿Divyesh。只需创建一个类似下面的指令即可回答提供并将其应用到代码中的任何位置。
  • 我已经更新了答案,请立即查看
  • 还是不行
  • 你检查过这个吗?
  • 是的,它仍然在接受 + 。 ? !一切

标签: typescript ionic-framework angular7 ionic4


【解决方案1】:

你应该使用按键事件 这是示例 TS 文件

  numberOnlyValidation(event: any) {
    const pattern = /[0-9.,]/;
    let inputChar = String.fromCharCode(event.charCode);

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

HTML 文件

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

它将解决您的问题。

在 Ionic 5 中使用指令:

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 文件

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

【讨论】:

  • 试过这个,不行。它正在接受 + 。 ? !一切,它也更新 ngModel 以及所有这些特殊字符
  • 您好,请将模式所在的行替换为“const pattern = /[0-9]/;”
  • 试过了,还是不行
  • 这行得通,但文本到语音不会通过这个运行。 (现在处理)
【解决方案2】:

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

  1. 我用方法创建了一个 util 类:

export class StringUtil {
 
    /**
     * Removes all non numeric characters from string.
     * @param str string
     */
    static removeNonNumerics = (str: string) => str.replace(/\D/g, '');

}
  1. 创建了我的指令:

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);
    }

}
  1. 我已经在我的页面模块中导入了 InputIntegerDirective:

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. 最后在页面上使用它:

<ion-input type="text" inputmode="numeric" formControlName="deliveryTime" maxlength="3" placeholder="Tempo de Entrega" [required]="true" appInputInteger>
</ion-input>

这个指令在网络浏览器和我的移动设备上也很有效。

【讨论】:

  • 记得使用 type="text" inputmode="numeric" ,如果你使用 type="number" 它不会工作,因为它会尝试在 int 上使用 .replace (字符串方法)价值。 inputmode="numeric" 仅显示数字键盘(即使在输入文本上)。另一种选择是使用 type="tel"。
【解决方案3】:

像这样更改您的代码。希望能解决

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

【讨论】:

  • 试过这个,它不断增加值,即如果我输入 5 然后 + 然后它会显示 55. 之后,如果我输入 1 然后它显示 55551
  • 是的,我试过了。我正在 Android 设备上进行测试,但它没有按预期工作。
【解决方案4】:

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

第 1 步:创建一个仅限数字的指令并将其放置在指令文件夹中。

number-only.directive.ts

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 文件中。

import { NumberDirective } from './directive/number-only.directive';
@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [NumberDirective],
  exports: []
})
export class AppModule { }

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

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

【讨论】:

  • 它正在使用 标签,但我的问题是当我们使用 时,我尝试使用 ion-input 但它不起作用
  • 我试过你更新的答案,它不起作用。调试我控制台evt.which,它的所有键为0。它的 0 具有离子输入和仅输入
  • 亲爱的团队,我正在使用ionic3,我们想停止在离子输入框中输入数值,请帮助我
  • 它应该只允许字母而不是数字
猜你喜欢
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多