Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

regex - How to allow only 4 digit numbers in html textbox?

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/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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).

So, use just 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...