HTML 5 - 数字正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16883549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:00:15  来源:igfitidea点击:

HTML 5 - number regular expression

html

提问by munue

I have got an input field called Fleet no.

我有一个名为 Fleet no 的输入字段。

I want to validate it using HTML 5 to only allow the input of digits to 5 digit max length.

我想使用 HTML 5 来验证它只允许输入 5 位最大长度的数字。

I have managed to only input digits but it only accepts 1 digit.

我设法只输入数字,但它只接受 1 位数字。

I can't put more than 1 digit. This is what i tried to do:

我不能输入超过 1 位数字。这就是我试图做的:

<div>
  <label for="element_1">Fleet Number </label>
  <input id="element_1" name="element_1" type="text" maxlength="255" 
  value="" required placeholder="Enter Digits only" pattern = "[0-9]"
  title='Fleet No. must contain digits only'/> 
</div>

回答by Nikola Mitev

This is the cleanest way

这是最干净的方式

<input type="text" pattern="\d{1,5}" title="Only digits" />

回答by Wouter J

Use [0-9]{1,5}

[0-9]{1,5}

{1,5}means repeat the previous part 1, 2, 3, ..., 5 times.

{1,5}表示重复前面的部分 1, 2, 3, ..., 5 次。

回答by Andre Elrico

why not for eg: using minand maxarguments for numberinput:

为什么不例如:使用min和输入max参数number

<input type="number" name="element_1" min="0" max="99999">

This is only valid when the number is smaller than 99999and this means it is less or equal to 5 digits.

这仅在数字小于时有效99999,这意味着它小于或等于 5 位。