I have simple text input:
<div style="float:right" class="xField">
<input id="userLength" name="userLength"/>
<label style="margin-left: 3px;">m</label>
</div>
I need this input to only accept numbers and if the number is a whole number, it should only allow 5 characters i.e. 12345
. If the number includes a fraction, it should then allow for 8 characters i.e. 12345,99
.
I've tried adding maxlength
to the input but that only works with one of these conditions at a time.
How can I accomplish this?
The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.
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.
Allow Only Numbers in Angular Form Input For handling only numbers in the input box we simply add an input control with the ( keypress ) event handler to call the keyPressNumbers() . Below is the code snippet for this along with the output. You clearly see that only numbers are present in the input box.
You could use the pattern
attribute and provide a regular expression that supports your requirements.
for example (this does not forbid entering invalid data, but will mark the field as invalid while the pattern is not matched).
<div style="float:right" class="xField">
<input id="userLength" name="userLength" pattern="\d{1,5}(,\d{1,2})?" />
<label style="margin-left: 3px;">m</label>
</div>
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