Reputation: 29
I want maxLength Validation in in HTML5.
I tried like this
<input type="number" name="trainer_mobile_no[]" maxlength="10" class="form-control" required="required"/>
Upvotes: 2
Views: 20297
Reputation: 26
you can use javascript in oninput like this:
<input type="number" name="contactNo" id="contactNo" class="form-control" placeholder="Enter Contact No" aria-label="contactNo" aria-describedby="basic-addon2" maxlength="10" data-rule-maxlength="10" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
Upvotes: 0
Reputation: 2491
There are two possibilities
<input type="number" min="1" max="999" />
and
if you want to check the length.
User will not be allowed to enter more than 4 digits
<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==5) return false;" />
Sample Code Given below.. run that
It will accept min 1 and max 999 numbers<br/>
<input type="number" min="1" max="999" />
<br/><br/>
and
<br/><br/>
if you want to check the length (max 5 is defined).<br/>
<input type="number" pattern="/^-?\d+\.?\d*$/" onKeyPress="if(this.value.length==5) return false;" />
Upvotes: 0
Reputation: 11
You cannot set maxlength attr for number type, you can achieve this by returning keypress event false in jQuery.
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
var maxlengthNumber = parseInt($('#quantity').attr('maxlength'));
var inputValueLength = $('#quantity').val().length + 1;
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
if(maxlengthNumber < inputValueLength) {
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Number : <input maxlength="8" type="number" name="quantity" id="quantity" />
Upvotes: 1
Reputation: 508
Use as
<input type="number" name="trainer_mobile_no[]" min="1" max="5" class="form-control" required="required">
Upvotes: 0
Reputation: 458
you can add a max attribute that will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max and a min value you can specify the range of allowed values:
<input type="number" min="1" max="999" />
Upvotes: 0
Reputation: 56
You cannot set max length but max value for number input type something like this:
<input type="number" min="0" max="100">
Upvotes: 1