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/>
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.
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.
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.
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With