I have type=number
input field and I have set min
and max
values for it:
<input type="number" min="0" max="23" value="14">
When I change the time in the rendered UI using the little arrows on the right-hand side of the input field, everything works properly - I cannot go either above 23 or below 0. However, when I enter the numbers manually (using the keyboard), then neither of the restrictions has effect.
Is there a way to prevent anybody from entering whatever number they want?
In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters. As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.
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.
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.
Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript
With HTML5 max
and min
, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data-
attributes and save the old value:
$(function () { $("input").keydown(function () { // Save old value. if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0)) $(this).data("old", $(this).val()); }); $("input").keyup(function () { // Check correct, else revert back to old value. if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0)) ; else $(this).val($(this).data("old")); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type="number" min="0" max="23" value="14" />
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