如何在HTML文本框中仅允许4位数字? [英] How to allow only 4 digit numbers in html textbox?

查看:597
本文介绍了如何在HTML文本框中仅允许4位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制用户在HTML文本框中仅插入4位数的数字0-9.

I have tried to restrict users in HTML text box to insert only 4 digit numbers 0-9.

我尝试了如下操作,但是它只允许使用两位数字.

I have tried as follows but it restrict only to allow two digit numbers.

<input type="text"  name="pincode" maxlength="4"  id="pin" pattern="^0[1-9]|[1-9]\d$" required/>

推荐答案

让我澄清一下:^[0-9]{4}$^\d{4}$中的任何一个都是有效的正则表达式,只能将值限制为4位数字.但是, pattern HTML5属性值已经固定默认情况下:

Let me clarify: any of the ^[0-9]{4}$ or ^\d{4}$ are valid regexps to restrict values to 4 digits only. However, pattern HTML5 attribute value is already anchored by default:

用于此属性的正则表达式语言与JavaScript中使用的正则表达式语言相同,只是 pattern属性与整个值匹配,而不仅仅是所有子集(类似于它在模式的开头暗示了^(?:,在模式的结尾暗示了)$ ).

The regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).

因此,只需使用pattern="\d{4}":

input:valid {
  color: green;
}
input:invalid {
  color: red;
}

<form name="form1"> 
 <input type="text"  name="pincode" maxlength="4"  id="pin" pattern="\d{4}" required/>
 <input type="Submit"/> 
</form>

顺便说一句,您的^0[1-9]|[1-9]\d$模式仅匹配2位数字的输入,因为它匹配0后跟19的任何数字,或者匹配19的任何数字,然后是任何数字

BTW, your ^0[1-9]|[1-9]\d$ pattern matches only 2 digit inputs because it matches either 0 followed by any digit from 1 to 9, or any digit from 1 to 9 followed by any digit.

此外,请注意pattern="\d{4}"属性不会阻止在字段中输入非数字符号.请参阅如何防止输入无效字符输入字段发布解决方法.

Also, note that pattern="\d{4}" attribute does not prevent entering non-digit symbols into the field. See How to prevent invalid characters from being typed into input fields post how to solve that.

这篇关于如何在HTML文本框中仅允许4位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆