Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only 4 digit numbers in html textbox?

Tags:

html

regex

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/>
like image 287
Nur Selam Avatar asked Jan 01 '16 12:01

Nur Selam


People also ask

How do I restrict only numbers in a text box in HTML?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.

How do I restrict only 10 numbers in a text box in HTML?

Firstly, create an array that stores all the ASCII codes or values of the digits 0 (ASCII value 48) through 9 (ASCII value 57) so that the input in the textbox can be validated later on. Next, set the max length of the input to 10 using maxlength attribute of the input tag.

How do you input numbers only in HTML?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict only input numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.


1 Answers

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>

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.

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.

like image 102
Wiktor Stribiżew Avatar answered Oct 11 '22 12:10

Wiktor Stribiżew