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>
Unlike the regular expression syntax used in programming languages, HTML5 does not require '^' and '$' to annotate the beginning and ending of values (it is assumed). Regular expressions can be enforced on inputs by using the “pattern” attribute.
The pattern attribute specifies a regular expression that the <input> element's value is checked against on form submission. Note: The pattern attribute works with the following input types: text, date, search, url, tel, email, and password. Tip: Use the global title attribute to describe the pattern to help the user.
The <input type="number"> defines a field for entering a number. Use the following attributes to specify restrictions: max - specifies the maximum value allowed. min - specifies the minimum value allowed.
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.
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.
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