Reputation: 449
I have got an input field called Fleet no.
I want to validate it using HTML 5 to only allow the input of digits to 5 digit max length.
I have managed to only input digits but it only accepts 1 digit.
I can't put more than 1 digit. This is what i tried to do:
<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>
Upvotes: 17
Views: 106989
Reputation: 6524
pattern
attribute only work after submit (button/enter), and you may need required="required"
to check if the input is empty.
<form>
<input type="text"
pattern="\d{1,5}"
required="required"
placeholder="enter or submit to verify" />
<button type="">submit</button>
</form>
for realtime check use HTMLFormElement.reportValidity()
function check(input) {
if (!/^\d{1,5}$/.test(input.value)) {
input.reportValidity()
}
}
<form>
<input type="text" pattern="\d{1,5}"
required="required"
oninput="check(this)"/>
<button type="">submit</button>
</form>
Upvotes: 0
Reputation: 153
Just add the below oninput expression into your HTML tag. This will allow accepting the only numbers between 0 to 9.
This one also restricts accepting +, -, .(dot).
<input type="text" id="salary" name="salary" maxlength="3" oninput="this.value = this.value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');" />
'OR'
<input type="text" id="salary" name="salary" maxlength="3" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
I found this in one of the js fiddles, and It works for me.
Upvotes: 3
Reputation: 41934
Use [0-9]{1,5}
<input type="text" pattern="[0-9]{1,5}" />
{1,5}
means repeat the previous part 1, 2, 3, ..., 5 times.
Upvotes: 19
Reputation: 4212
This is the cleanest way
<input type="text" pattern="\d{1,5}" title="Only digits" />
Upvotes: 14
Reputation: 11
only 5 digit numeric:
See: https://regex101.com/r/pTSwFN/1/
pattern="[0-9]{5}"
Upvotes: 0
Reputation: 11480
why not for eg: using min
and max
arguments for number
input:
<input type="number" name="element_1" min="0" max="99999">
This is only valid when the number is smaller than 99999
and this means it is less or equal to 5 digits.
Upvotes: 1