全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-17 5 分钟 ✍️ juanwangdev

HTML minlength和maxlength属性

minlength和maxlength属性用于限制文本输入框的最小和最大字符数,浏览器在表单提交时自动进行长度验证。

基本语法

HTML
<input type="text" minlength="最小长度" maxlength="最大长度">
<textarea minlength="最小长度" maxlength="最大长度"></textarea>

属性说明

属性说明验证失败状态
minlength最小字符数validity.tooShort = true
maxlength最大字符数validity.tooLong = true

代码示例

基本用法

HTML
<form>
  <label>用户名(6-12位):</label>
  <input type="text" name="username"
         minlength="6" maxlength="12" required>
  <br><br>

  <label>密码(8-16位):</label>
  <input type="password" name="password"
         minlength="8" maxlength="16" required>
  <br><br>

  <button type="submit">提交</button>
</form>

textarea长度限制

HTML
<form>
  <label>个人简介(20-200字):</label>
  <br>
  <textarea name="bio"
            minlength="20"
            maxlength="200"
            rows="4"
            cols="40"
            placeholder="请输入20-200字的个人简介"></textarea>
  <span id="bioCount">0/200</span>
  <br><br>

  <button type="submit">提交</button>
</form>

<script>
  const textarea = document.querySelector('textarea');
  const count = document.getElementById('bioCount');

  textarea.addEventListener('input', () => {
    count.textContent = `${textarea.value.length}/200`;
  });
</script>

maxlength阻止输入

HTML
<style>
  .char-counter {
    font-size: 12px;
    color: #666;
  }

  .char-counter.warning {
    color: #f39c12;
  }

  .char-counter.danger {
    color: #e74c3c;
  }
</style>

<form>
  <label>评论(最多100字):</label>
  <br>
  <textarea name="comment" id="comment"
            maxlength="100"
            rows="3"
            cols="40"></textarea>
  <span id="charCounter" class="char-counter">0/100</span>
  <br>
  <button type="submit">提交</button>
</form>

<script>
  const comment = document.getElementById('comment');
  const counter = document.getElementById('charCounter');

  comment.addEventListener('input', () => {
    const len = comment.value.length;
    counter.textContent = `${len}/100`;

    counter.classList.remove('warning', 'danger');
    if (len >= 100) {
      counter.classList.add('danger');
    } else if (len >= 80) {
      counter.classList.add('warning');
    }
  });
</script>

minlength验证反馈

HTML
<style>
  input:invalid:not(:placeholder-shown) {
    border-color: #e74c3c;
  }

  input:valid {
    border-color: #27ae60;
  }

  .hint {
    font-size: 12px;
    color: #999;
  }

  .error {
    color: #e74c3c;
  }
</style>

<form id="pwdForm">
  <label>密码:</label>
  <input type="password" id="password"
         minlength="8" maxlength="16"
         required placeholder="8-16位字符">
  <span id="pwdHint" class="hint">请输入8-16位密码</span>
  <br><br>

  <button type="submit">提交</button>
</form>

<script>
  const password = document.getElementById('password');
  const hint = document.getElementById('pwdHint');

  password.addEventListener('input', () => {
    const v = password.validity;

    if (v.tooShort) {
      hint.textContent = `还差${8 - password.value.length}个字符`;
      hint.className = 'error';
    } else if (v.tooLong) {
      hint.textContent = '超出最大长度限制';
      hint.className = 'error';
    } else {
      hint.textContent = '密码格式正确';
      hint.className = 'hint';
    }
  });
</script>

实时字数统计

HTML
<form>
  <label>文章标题(5-50字):</label>
  <input type="text" id="title"
         minlength="5" maxlength="50"
         placeholder="请输入标题">
  <span id="titleCount"></span>
  <br><br>

  <label>文章内容(100-5000字):</label>
  <br>
  <textarea id="content"
            minlength="100" maxlength="5000"
            rows="8" cols="60"></textarea>
  <span id="contentCount"></span>
  <br><br>

  <button type="submit">发布文章</button>
</form>

<script>
  function setupCounter(inputId, counterId, min, max) {
    const input = document.getElementById(inputId);
    const counter = document.getElementById(counterId);

    input.addEventListener('input', () => {
      const len = input.value.length;
      counter.textContent = `${len}/${max}`;

      if (len < min) {
        counter.textContent += `(至少还需${min - len}字)`;
        counter.style.color = '#e74c3c';
      } else if (len > max * 0.9) {
        counter.style.color = '#f39c12';
      } else {
        counter.style.color = '#27ae60';
      }
    });
  }

  setupCounter('title', 'titleCount', 5, 50);
  setupCounter('content', 'contentCount', 100, 5000);
</script>

JavaScript检测

HTML
<form id="testForm">
  <input type="text" id="testInput" minlength="3" maxlength="10">
  <button type="submit">提交</button>
</form>

<script>
  const input = document.getElementById('testInput');

  input.addEventListener('input', () => {
    console.log('值长度:', input.value.length);
    console.log('太短:', input.validity.tooShort);
    console.log('太长:', input.validity.tooLong);
    console.log('验证通过:', input.validity.valid);
  });

  // 动态设置长度限制
  input.minLength = 5;  // 设置最小长度
  input.maxLength = 20;  // 设置最大长度
</script>

minlength与maxlength的区别

特性minlengthmaxlength
验证时机表单提交时输入时+提交时
用户可输入可超出限制超出后无法输入
验证失败validity.tooShortvalidity.tooLong

注意:maxlength会阻止用户输入超过限制的字符,而minlength只在提交时验证。建议配合实时字数统计提升用户体验。

要点总结

  1. minlength设置最小字符数,maxlength设置最大字符数
  2. maxlength会阻止超出字符的输入
  3. 验证失败时validity.tooShort或validity.tooLong为true
  4. 适用于input(text/password/email等)和textarea
  5. 建议配合实时字数统计提示用户

📝 发现内容有误?点击此处直接编辑

← 上一篇 HTML checkValidity和reportValidity
下一篇 → HTML min和max属性
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库