简体   繁体   English

Angular - 文本输入字段只接受手机中的数字

[英]Angular -Text Input Field To Accept Only Numbers in Mobile Phones

In angular 9, I created an input field text which only accepts number using this code:在 angular 9 中,我使用以下代码创建了一个仅接受数字的输入字段文本:

Html File: html文件:

<mat-form-field>
<mat-label>{{fields.label}}</mat-label>
<input
 pattern="[0-9]*"
 [formControlName]="fields.field"
 [id]="fields.field"
 [type]="'text'"
 (keypress)="numericOnly($event)"
 autocomplete="off"
 matInput>
</mat-form-field>

Typescript file:打字稿文件:

numericOnly(event): boolean {
    return !isNaN(Number(event.key)) && event.key !== ' ';
  }

This code is working properly in DESKTOP web browser but my problem is when I access the site in MOBILE PHONE the input field doesn't only accepts numbers but accepts chars.此代码在桌面网络浏览器中正常工作,但我的问题是当我在移动电话中访问站点时,输入字段不仅接受数字而且接受字符。

Please help me to solve this in mobile phones.请帮我在手机上解决这个问题。 I still need this to work in safari, chrome and mozilla mobile phone.我仍然需要它在 safari、chrome 和 mozilla 手机中工作。 Thanks guys..谢谢你们..

// It will help you // 它会帮助你

numbersOnly(event) {
        const input = String.fromCharCode(event.keyCode);
        if (!/^[0-9]*$/.test(input)) {
            event.preventDefault();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM