简体   繁体   English

仅包含数字的文本框

[英]Textbox with numbers only

I can see all over following suggestion is recommended for having a textbox with numbers only: 我可以看到以下建议,建议只使用数字的文本框:

 <input  formControlName="imo" class="form-control" pattern="\d*" maxlength="8">

But for me I can enter characters and are not restricted to numbers only. 但是对我来说,我可以输入字符,而不仅限于数字。 I am using latest version of Crome. 我正在使用最新版本的Crome。 Is this a side affect of the formControlName in my Angular app or have I misunderstod the pattern part? 这是Angular应用程序中formControlName的副作用,还是我误解了模式部分?

pattern just checks if the value is valid or not, it does not interfere with what user is typing. pattern仅检查该值是否有效,它不会干扰用户键入的内容。 If you want to allow only numeric values, and that digits entered aren't more than 5 (as you say in comment), then you can do this: 如果您只允许数字值,并且输入的数字不超过5(如您在注释中所述),则可以执行以下操作:

<input type="text" formControlName="imo" (keypress)="checkValue($event)">

and the function: 和功能:

checkValue(event) {
  return event.target.value.length === 5 ? event.preventDefault() : 
    String.fromCharCode(event.charCode).match(/[^0-9]/g) === null
}

StackBlitz StackBlitz

This will actually block the input. 这实际上将阻止输入。 If it's suitable with not blocking values, you can go ahead and use Validators.pattern() and then just show an error message when user types something they shouldn't. 如果适合使用不阻塞值的方法,则可以继续使用Validators.pattern() ,然后在用户键入不应输入的内容时显示错误消息。

我认为这是您要寻找的:

<input type="number" formControlName="imo" class="form-control" min="1" max="5">

Hello have you tried this below 你好你在下面尝试过

\\d+ instead of \\d* \\ d +而不是\\ d *

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

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