HTML - maxlength Attribute



HTML maxlength attribute is used to define the maximum number of characters the user can enter into an input and textarea field.

If no maxlength value is specified, or any invalid value is specified, the input and textarea have no maximum length. The maxlength value must be greater than or equal to the value of the minlength attribute.

Syntax

<tag maxlength = "value">

Applies On

Below listed elements allow using of the HTML maxlength attribute

Element Description
<input> HTML <input> tag is used accpect various types of input from user.
<textarea> HTML <textarea> tag is used to represent a multiline plain-text editing control.

Examples of maxlength Attribute

Below examples will illustrate the HTML maxlength attribute, where and how we should use this attribute!

Set maxlength on input

In the following example, we are going to use maxlength attribute with the input type=text to set maximum length for name input is 10.

<!DOCTYPE html>
<html lang="en">
      
<head>
   <title>HTML 'maxlength' attribute</title>
</head>

<body>
   <form>
      <input type="text" 
             maxlength="10" 
             placeholder="Enter Name">
      <br><br>
      <button>Submit</button>
   </form>
</body>

</html>

Set maxlength on textarea

Considering the another case, where we are going to use the maxlength attribute with the textarea element to set maximum acceptable length of characters in textarea as 30.

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML 'maxlength' attribute</title>
</head>

<body>
   <form> Write your feedback: <br>
      <textarea name="" 
                id="" 
                cols="30" 
                rows="5" 
                placeholder="Your feedback...." 
                maxlength="30">
      </textarea>
      <br>
      <button>Submit</button>
   </form>
</body>

</html>

Supported Browsers

Attribute Chrome Edge Firefox Safari Opera
maxlength Yes 1.0 Yes 10.0 Yes 4.0 Yes 1.0 Yes 15.0
html_attributes_reference.htm
Advertisements