Is there a minlength validation attribute in HTML? - html

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?

You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">

There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.

Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>

Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.

I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`

minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />

The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>

Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.

My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>

See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">

New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}

I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}

In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.

I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>

If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;

Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.

Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">

I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />

Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />

Related

How to Include space on number input?

How to include the spaces (not text,
only spaces and numbers) on the input type?
When i try my code it only includes numbers
This is my code:
<form action="/action_page.php"><input type="number"/><input type="submit"</form>
You need to use type="text" for your input in order to format your value as you want. type="number" does not work with this kind of format.
const formatter = new Intl.NumberFormat('fr-FR');
<input
type="text"
value={formatter.format(value)}
/>
<form action="/action_page.php">
<input type="text" pattern="[0-9 ]+" />
<input type="submit"</form>
you can use input with type text and add pattern "[0-9 ]+".
This option is perfect for me.
<input type = "text" inputmode = "numeric">
input.addEventListener("input", inputEvent => {
input.value = input.value.replaceAll(/\D/g, "");
if (inputEvent.inputType === "insertText"){
input.value = new Intl.NumberFormat().format(value);
}
}

Allow 2 decimal places in <input type="number">

I have a <input type="number"> and I want to restrict the input of the users to purely numbers or numbers with decimals up to 2 decimal places.
Basically, I am asking for a price input.
I wanted to avoid doing regex. Is there a way to do it?
<input type="number" required name="price" min="0" value="0" step="any">
Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.
More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute
In case anyone is looking for a regex that allows only numbers with an optional 2 decimal places
^\d*(\.\d{0,2})?$
For an example, I have found solution below to be fairly reliable
HTML:
<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />
JS / JQuery:
$(document).on('keydown', 'input[pattern]', function(e){
var input = $(this);
var oldVal = input.val();
var regex = new RegExp(input.attr('pattern'), 'g');
setTimeout(function(){
var newVal = input.val();
if(!regex.test(newVal)){
input.val(oldVal);
}
}, 1);
});
For currency, I'd suggest:
<div><label>Amount $
<input type="number" placeholder="0.00" required name="price" min="0" value="0" step="0.01" title="Currency" pattern="^\d+(?:\.\d{1,2})?$" onblur="
this.parentNode.parentNode.style.backgroundColor=/^\d+(?:\.\d{1,2})?$/.test(this.value)?'inherit':'red'
"></label></div>
See http://jsfiddle.net/vx3axsk5/1/
The HTML5 properties "step", "min" and "pattern" will be validated when the form is submit, not onblur. You don't need the step if you have a pattern and you don't need a pattern if you have a step. So you could revert back to step="any" with my code since the pattern will validate it anyways.
If you'd like to validate onblur, I believe giving the user a visual cue is also helpful like coloring the background red. If the user's browser doesn't support type="number" it will fallback to type="text". If the user's browser doesn't support the HTML5 pattern validation, my JavaScript snippet doesn't prevent the form from submitting, but it gives a visual cue. So for people with poor HTML5 support, and people trying to hack into the database with JavaScript disabled or forging HTTP Requests, you need to validate on the server again anyways. The point with validation on the front-end is for a better user experience. So as long as most of your users have a good experience, it's fine to rely on HTML5 features provided the code will still works and you can validate on the back-end.
Step 1: Hook your HTML number input box to an onchange event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the HTML code
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
You can alter the number of decimal places by varying the value passed into the toFixed() method. See MDN docs.
toFixed(2); // 2 decimal places
toFixed(4); // 4 decimal places
toFixed(0); // integer
Try this for allowing only 2 decimal in input type
<input type="number" step="0.01" class="form-control" />
Or Use jQuery as suggested by #SamohtVII
$( "#ELEMENTID" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
I had the same requirement but after checking all these answers I realized there is no inbuilt support to block users from typing a particular number of decimal points. step="0.01" is useful when validating the input for a decimal number but still it will not block users from typing any decimal. In my case, I wanted a solution which will prevent user from entering invalid decimal. So I created my own custom JavaScript function which will enforce user any decimal rule. There is a slight performance issue but for my scenario it is okay to have a very small delay to make sure that user is not typing invalid decimal places. It might be useful for someone who wanted to prevent user from typing invalid decimal value on the input.
You can use this solution with step="0.01" if you want. You can use the below function on your element oninput event. If performance is critical for you, then think to use this on onchange event rather than oninput. And please specify maximum number of decimal places allowed in the input in data-decimal attribute. it can have values from 0 to any number.
function enforceNumberValidation(ele) {
if ($(ele).data('decimal') != null) {
// found valid rule for decimal
var decimal = parseInt($(ele).data('decimal')) || 0;
var val = $(ele).val();
if (decimal > 0) {
var splitVal = val.split('.');
if (splitVal.length == 2 && splitVal[1].length > decimal) {
// user entered invalid input
$(ele).val(splitVal[0] + '.' + splitVal[1].substr(0, decimal));
}
} else if (decimal == 0) {
// do not allow decimal place
var splitVal = val.split('.');
if (splitVal.length > 1) {
// user entered invalid input
$(ele).val(splitVal[0]); // always trim everything after '.'
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" data-decimal="0" oninput="enforceNumberValidation(this)" placeholder="No decimal places" value="" />
<input type="number" data-decimal="2" oninput="enforceNumberValidation(this)" placeholder="2 decimal places" value="" />
<input type="number" data-decimal="5" oninput="enforceNumberValidation(this)" placeholder="5 decimal places" value="" />
I might use RegExp to identify invalid value but I have to revert the change in the input as well. So I decided to not use RegExp.
just adding step=".01", sorted my issue.
<input type="number" class="form-control" name="price" step=".01">
Use this code
<input type="number" step="0.01" name="amount" placeholder="0.00">
By default Step value for HTML5 Input elements is step="1".
I had a strange editing experience with some of these solutions. This seems to work pretty well from a user's perspective (only intervene when necessary):
function handleNumberChanged (e) {
const fixed = parseFloat(e.target.value).toFixed(2).toString()
if (fixed.length < parseFloat(e.target.value).toString().length)
e.target.value = fixed
}
This question has been already answer but you can allow decimals
with the step attribute.
you can read more about it here: Allow-decimal-values
This is the solution I've came up with which also stops the user from typing in more that 2 decimals, which a lot of the solutions mentioned above, don't protect against
html:
<input autocomplete="off" type="number" id="priceField" step=".01" min="0" onkeypress="return priceCheck(this, event);"
Javascript:
function priceCheck(element, event) {
result = (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 46;
if (result) {
let t = element.value;
if (t === '' && event.charCode === 46) {
return false;
}
let dotIndex = t.indexOf(".");
let valueLength = t.length;
if (dotIndex > 0) {
if (dotIndex + 2 < valueLength) {
return false;
} else {
return true;
}
} else if (dotIndex === 0) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Only 3 decimal point input value in textbox using Javascript.
<input type="text" class="form-control" onkeypress='return AllowOnlyAmountAndDot(this,event,true);/>
function AllowOnlyAmountAndDot(id, e, decimalbool) {
if(decimalbool == true) {
var t = id.value;
var arr = t.split(".");
var lastVal = arr.pop();
var arr2 = lastVal.split('');
if (arr2.length > '2') {
e.preventDefault();
}
}
}
<input type="number" class="form-control" id="price" oninput="validate(this)" placeholder="Enter price" name="price" style="width:50%;">
var validate = function(e) {
var t = e.value;
e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
On Input:
<input type="number" name="price" id="price" required>
On script:
$('#price').on('change', function() {
var get_price = document.getElementById('price').value;
var set_price = parseFloat(get_price).toFixed(2);
$('input[name=price').val(set_price);
})
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
just write
<input type="number" step="0.1" lang="nb">
lang='nb" let you write your decimal numbers with comma or period
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});

How can I create a custom message when an HTML5 required input pattern does not pass?

I have the following:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />
When I enter just one character I get a message saying:
"Please match the requested format"
Is there a way I can customize this message to say something like "Please enter at least 5 characters"
You can do a quick and dirty way with this trick:
<form>
<label for="username">Username:</label><br/>
<input id="username" type="text" pattern=".{6,}" autofocus required title="Please enter at least 5 characters">
<input id="submit" type="submit" value="create">
</form>
Use: setCustomValidity
First function sets custom error message:
$(function(){
$("input[name=Password]")[0].oninvalid = function () {
this.setCustomValidity("Please enter at least 5 characters.");
};
});
Second function turns off custom message. Without this function custom error message won't turn off as the default message would:
$(function(){
$("input[name=Password]")[0].oninput= function () {
this.setCustomValidity("");
};
});
P.S. you can use oninput for all input types that have a text input.
For input type="checkbox" you can use onclick to trigger when error should turnoff:
$(function(){
$("input[name=CheckBox]")[0].onclick= function () {
this.setCustomValidity("");
};
});
For input type="file" you should use change.
The rest of the code inside change function is to check whether the file input is not empty.
P.S. This empty file check is for one file only, feel free to use any file checking method you like as well as you can check whether the file type is to your likes.
Function for file input custom message handling:
$("input[name=File]").change(function () {
let file = $("input[name=File]")[0].files[0];
if(this.files.length){
this.setCustomValidity("");
}
else {
this.setCustomValidity("You forgot to add your file...");
}
//this is for people who would like to know how to check file type
function FileType(filename) {
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
if(FileType(file.name)!="pdf"||FileType(file.name)!="PDF"){
this.setCustomValidity("Your file type has to be PDF");
//this is for people who would like to check if file size meets requirements
else if(file.size/1048576>2){
// file.size divided by 1048576 makes file size units MB file.size to megabytes
this.setCustomValidity("File hast to be less than 2MB");
}
else{
this.setCustomValidity("");
}
});//file input custom message handling function
HTML5 form required attribute. Set custom validation message?
JSFiddle: http://jsfiddle.net/yT3w3/
Non-JQuery solution:
function attachHandler(el, evtname, fn) {
if (el.addEventListener) {
el.addEventListener(evtname, fn.bind(el), false);
} else if (el.attachEvent) {
el.attachEvent('on' + evtname, fn.bind(el));
}
}
attachHandler(window, "load", function(){
var ele = document.querySelector("input[name=Password]");
attachHandler(ele, "invalid", function () {
this.setCustomValidity("Please enter at least 5 characters.");
this.setCustomValidity("");
});
});
JSFiddle: http://jsfiddle.net/yT3w3/2/
I'd add another attribute oninvalid.
oninvalid="setCustomValidity('Please enter at least 5 characters')"
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" oninvalid="setCustomValidity('Please enter at least 5 characters')"/>
I found that, chrome at least, adds to the message the title of the input automatically, so no extra js is required, see this:
the input looks like this:
<input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">
It is very simple without javascript or jQuery validation. We can achieve it by HTML5
Let suppose we have HTML field:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />
Just change the HTML as
<input required pattern=".{6,}" class="big medium-margin" title="Please enter at least 5 characters." name="Password" placeholder="Password" size="25" type="password" />
If you observe, just add title = "Error message"
Now whenever form will be post, the given messages will be appeared and we did not need JavaScript or jQuery check.
This solution works for me.
I simply use oninvalid to set the custom validty error message and then use onchange to reset the message so the form can submit.
<input type="number" oninvalid="this.setCustomValidity('Please enter an INTEGER')" onchange="this.setCustomValidity('')" name="integer-only" value="0" min="0" step="1">
You'd need to use the setCustomValidity function. The problem with this is that it'd only guarantee a custom message for users who have JavaScript enabled.
<input required pattern=".{6,}" ... oninput="check(this)">
^^^^^^^^^^^^^^^^^^^^^
function check (input) {
if (input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0) {
// Input is fine. Reset error message.
input.setCustomValidity('');
} else {
input.setCustomValidity('Your custom message here.');
}
}
https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<input id="gfg" type="number" min="101" max="999" required>
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>

HTML maxlength attribute not working on chrome and safari?

<input type="number" maxlength="5" class="search-form-input" name="techforge_apartmentbundle_searchformtype[radius]" id="techforge_apartmentbundle_searchformtype_radius">
This is my HTML, taken with firebug (on chrome).
I am allowed to write as much as characters as I want in the form field - in Chrome and Safari.
When on Firefox or IE10, the limit is fine.
I haven't found this issue around on the net.
Note: type="number" - not text.
Anyone saw this issue before?
Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength. Please see the below code.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
Use the max attribute for inputs of type="number". It 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" />
See this example
EDIT
If, for user experience, you would prefer the user not to be able to enter more than a certain number, use Javascript/jQuery, as seen in this example
The maxlength attribute does not apply to an input of type="number"
From W3 HTML5 spec concerning type="number"
The following content attributes must not be specified and do not
apply to the element: accept, alt, checked, dirname, formaction,
formenctype, formmethod, formnovalidate, formtarget, height,
maxlength, multiple, pattern, size, src, and width.
Source: http://dev.w3.org/html5/spec/Overview.html#number-state-type-number
(under Bookkeeping details)
In FF and IE, the input is falling back to be a text input and therefore, maxlength applies to the input. Once FF and IE implement type="number", they should also implement it in a way where maxlength does not apply.
For those who still can't get it to work... Try this to fire up the fatter number pads:
<input type="number" name="no1" maxlength="1" size="1" max="9" pattern="[0-9]*" />
And the js:
$('input[name="no1"]').keypress(function() {
if (this.value.length >= 1) {
return false;
}
});
Here is an example using type="number" and maxlength, that works with Chrome, IE and others. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function test(id, event) {
var element = $("#" + id);
var len = element.val().length + 1;
var max = element.attr("maxlength");
var cond = (46 < event.which && event.which < 58) || (46 < event.keyCode && event.keyCode < 58);
if (!(cond && len <= max)) {
event.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input id="test" size="3" type="number" maxlength="3" onkeypress="test(this.id, event)">
</body>
</html>
Speaking of HTML 4.01 there is no such type as "number".
Speaking of HTML 5 FF and IE do not yet know the number type if http://www.w3schools.com/html5/html5_form_input_types.asp is correct.
/edit: So FF and IE will probably fallback to text and this is why maxlength will work.
I solved problem using this jQuery codes:
$('input[type="number"]').on('keypress', function (e) {
var maxlength = $(this).prop('maxlength');
if (maxlength !== -1) { // Prevent execute statement for non-set maxlength prop inputs
var length = $(this).val().trim().length;
if (length + 1 > maxlength) e.preventDefault();
}
});
Set maxlength attribute for every input[type="number"] that you want, just like text inputs.
for react this works for me if anyone stumbles on here with using react :)
<input type="number" name="expiry" placeholder="Expiry" onChange=
{this.handleInputChange} onFocus={this.handleInputFocus} onInput={(event)=>event.target.value=event.target.value.slice(0,event.target.maxLength)}
maxLength="4" />
for guys who are using React and have landed here:
<input name="maxNumber"
onInput= {(event)=> event.target.value.length > 1 ?
event.target.value =
event.target.value.slice(0, 1)
:
event.target.value
}
type = "number"
/>
In this case, 1 is the maximum length of values. You can put any and change the ones.

Limit number of characters allowed in form input text field

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?
Below is the input field as part of my form:
<input type="text" id="sessionNo" name="sessionNum" />
Is it using something like maxSize or something like that?
maxlength:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field
will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />
Add the following to the header:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);"
onKeyUp="limitText(this,5);"" />
Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.
According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.
Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway
<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.
Maxlength
The maximum number of characters that will be accepted as input.
The maxlength attribute specifies the maximum number of characters allowed in the element.
Maxlength W3 schools
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>
I always do it like this:
$(document).ready(function() {
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
maxChars.on('keyup', function(e) {
length = new Number(maxChars.val().length);
counter = max_length - length;
$("#sessionNum_counter").text(counter);
});
}
});
Input:
<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>
You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9"> for numbers
or
<input type = "email" maxlength="9"> for email
validation will show up
<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">
function maxLengthCheck(object) {
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}
The following code includes a counted...
var count = 1;
do {
function count_down(obj, count){
let element = document.getElementById('count'+ count);
element.innerHTML = 80 - obj.value.length;
if(80 - obj.value.length < 5){
element.style.color = "firebrick";
}else{
element.style.color = "#333";
}
}
count++;
} while (count < 20);
.text-input {
padding: 8px 16px;
width: 50%;
margin-bottom: 5px;
margin-top: 10px;
font-size: 20px;
font-weight: 700;
font-family: Raleway;
border: 1px solid dodgerblue;
}
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80" class="text-input" name="bikeTitle" ></p>
<span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:
Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.
Just Numbers:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);
Just Letters:
oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"
Full example:
<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>
Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />
<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>