Javascript input maxlength
Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute.
The maxLength attribute defines the maximum number of characters allowed in the input field.
NOTE: If the value of maxlength() attribute is not defined, then the default value is taken as 524288 by default.
This method is supported by mostly all the browsers like Google chrome, safari, Microsoft Edge/Internet Explorer, Oracle, Firefox etc.
Syntax:
<input maxlength="number">
Here, the number must be 0 or higher. It can take negative values.
Example:
<!DOCTYPE html>
<html>
<body>
<h3>The following is an example to demonstrate the input maxlength attribute</h3>
<form>
<label for="tcontent">Enter your text:</label>
<input type="text" id="tcontent" name="tcontent" maxlength="25">
<br>
</form>
</body>
</html>
Output:
The input filed won’t allow more than 25 characters to be entered in the input field:

Some key points:
- The length specified in maxlength should be 0 or more than 0.
- The minlength attribute can be defined to specify the minimum number of characters allowed in the input field for the input field. So, the value of maxlength should always be greater than or equal to the value of minlength (if it is present).
- Constraint validation will fail in the input if the field’s text length or value is greater than maxlength UTF-16 code units long. Constraint validation comes into purpose when the value is changed by the user.
What is Constraint validation?
The browser generally prevents ay user from entering more text than the maxlength attribute specifies. If by chance, the length of text entered by the user is longer than the maxlength allows, then the read-only tooLong property of a ValidityState object becomes true.
NOTE: If the user wants to find the width of an input filed, the size() property is used.
How is size() property used?
It takes the default value as 20.
Syntax:
To return the size of the field:
textObject.size
To set the size of the field:
textObject.size = “number”
Example:
Here, the example shows both the functionalities of size() property.
<!DOCTYPE html>
<html>
<body>
Enter text here: <input type="text" id="tcontent" size="30">
<p> Select the button to view the value of the size attribute in the input field.</p>
<button onclick="myFunctiondemo()">Click</button>
<p id="displaysize"></p>
<script>
function myFunctiondemo() {
var x = document.getElementById("tcontent").size;
document.getElementById("displaysize").innerHTML = x;
}
</script>
</body>
</html>
Output:

What is the difference between size and maxlength in HTML?
The max-length attribute is used to define the number of characters that can be entered in the input field irrespective of how wide the fields appears on the screen. However, the size attribute determines how large the field will appear on the screen.