Skip to content

minlength / maxlength

minlengthmaxlength 属性用于限制文本输入的字符长度。maxlength 限制用户可以输入的最大字符数(硬限制,超出部分无法输入),minlength 设置最小字符数(软限制,提交时验证)。这两个属性适用于 textsearchurltelemailpasswordtextarea 元素。

前置知识

阅读本节前,建议先了解:min / max / step

基础概念

maxlength 硬限制

maxlength 属性设置输入框可输入的最大字符数。用户输入的字符数达到该值后,浏览器将阻止继续输入。

  • 即时生效:在输入过程中就限制字符数
  • 不可突破:用户无法输入超过 maxlength 的字符
  • 包含所有字符:字母、数字、空格、标点符号都计入

minlength 软限制

minlength 属性设置输入框提交时允许的最小字符数。与 maxlength 不同,minlength 只在表单提交时验证。

  • 提交时验证:不在输入过程中限制
  • 可配合提示:使用 JavaScript 显示剩余/需要字符数
  • 空值豁免:如果字段为空,minlength 不会触发验证(需搭配 required

适用元素

元素maxlengthminlength
<input type="text">
<input type="search">
<input type="url">
<input type="tel">
<input type="email">
<input type="password">
<textarea>
<input type="number">

语法

maxlength 基本用法

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>maxlength 基本示例</title>
</head>
<body>
    <h2>短信内容</h2>
    <form>
        <label for="sms">短信内容(最多 70 字):</label>
        <input type="text" id="sms" name="sms" maxlength="70">
        <button type="submit">发送</button>
    </form>
</body>
</html>

minlength 基本用法

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>minlength 基本示例</title>
</head>
<body>
    <h2>密码设置</h2>
    <form>
        <label for="pwd">密码(至少 8 位):</label>
        <input type="password" id="pwd" name="password" minlength="8" required>
        <button type="submit">提交</button>
    </form>
</body>
</html>

同时使用 minlength 和 maxlength

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>minlength + maxlength</title>
</head>
<body>
    <h2>用户名</h2>
    <form>
        <label for="username">用户名(3-20 个字符):</label>
        <input
            type="text"
            id="username"
            name="username"
            minlength="3"
            maxlength="20"
            required
            placeholder="3-20 个字符"
        >
        <button type="submit">注册</button>
    </form>
</body>
</html>

详细说明

实时字数统计

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>字数统计</title>
    <style>
        body { font-family: sans-serif; max-width: 600px; margin: 40px auto; }
        .form-group { margin-bottom: 16px; }
        label { display: block; font-weight: 600; margin-bottom: 4px; }
        textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 15px;
            box-sizing: border-box;
            resize: vertical;
        }
        .char-count {
            text-align: right;
            font-size: 14px;
            margin-top: 4px;
        }
        .char-count.warning { color: #f39c12; }
        .char-count.error { color: #e74c3c; }
        .char-count.ok { color: #27ae60; }
    </style>
</head>
<body>
    <h2>字数统计器</h2>
    <form>
        <div class="form-group">
            <label for="bio">个人简介(10-200 字):</label>
            <textarea id="bio" name="bio" minlength="10" maxlength="200" rows="4"
                      placeholder="简单介绍一下自己..." oninput="updateCount()"></textarea>
            <div class="char-count" id="count">0 / 200</div>
        </div>
    </form>

    <script>
        function updateCount() {
            const textarea = document.getElementById('bio');
            const count = document.getElementById('count');
            const len = textarea.value.length;
            const min = textarea.minLength;
            const max = textarea.maxLength;

            count.textContent = `${len} / ${max}`;

            // 颜色提示
            count.className = 'char-count';
            if (len > max * 0.9) {
                count.classList.add('error');
            } else if (len < min && len > 0) {
                count.classList.add('warning');
                count.textContent = `${len} / ${max}(至少需要 ${min} 字)`;
            } else if (len >= min) {
                count.classList.add('ok');
            }
        }
    </script>
</body>
</html>

:too-short 和 :too-long 伪类

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>:too-short :too-long</title>
    <style>
        body { font-family: sans-serif; max-width: 600px; margin: 40px auto; }
        input, textarea {
            width: 100%;
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            box-sizing: border-box;
            margin-bottom: 12px;
        }

        /* 长度太短 */
        :too-short {
            border-color: #f39c12;
        }

        /* 长度太长 */
        :too-long {
            border-color: #e74c3c;
        }

        /* 长度合适 */
        :not(:too-short):not(:too-long) {
            border-color: #27ae60;
        }
    </style>
</head>
<body>
    <h2>长度伪类</h2>
    <form>
        <label for="username">用户名(3-20字符):</label>
        <input type="text" id="username" minlength="3" maxlength="20" value="a">
        <p>当前仅 1 个字符,边框为橙色(太短)。</p>

        <label for="desc">描述(5-50字符):</label>
        <textarea id="desc" minlength="5" maxlength="50">这是一个描述文本</textarea>
    </form>
</body>
</html>

textarea 字数限制

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>textarea 字数限制</title>
    <style>
        body { font-family: sans-serif; max-width: 600px; margin: 40px auto; }
        textarea { width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 6px; box-sizing: border-box; }
        .counter { display: flex; justify-content: space-between; margin-top: 4px; font-size: 14px; }
    </style>
</head>
<body>
    <h2>评论</h2>
    <form>
        <label for="comment">发表评论(10-500 字):</label>
        <textarea id="comment" name="comment" minlength="10" maxlength="500" rows="5"
                  placeholder="请输入您的评论..." oninput="countChars()"></textarea>
        <div class="counter">
            <span id="hint">至少输入 10 个字</span>
            <span id="remaining">剩余 500 字</span>
        </div>
        <button type="submit">发表</button>
    </form>

    <script>
        function countChars() {
            const ta = document.getElementById('comment');
            const len = ta.value.length;
            const min = ta.minLength;
            const max = ta.maxLength;
            const remaining = max - len;

            document.getElementById('remaining').textContent = `剩余 ${remaining} 字`;
            const hint = document.getElementById('hint');

            if (len === 0) {
                hint.textContent = `至少输入 ${min} 个字`;
                hint.style.color = '#666';
            } else if (len < min) {
                hint.textContent = `还需 ${min - len} 个字`;
                hint.style.color = '#e74c3c';
            } else {
                hint.textContent = '字数符合要求';
                hint.style.color = '#27ae60';
            }
        }
    </script>
</body>
</html>

实战示例

多字段字数限制表单

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>多字段字数限制</title>
    <style>
        body { font-family: sans-serif; max-width: 600px; margin: 40px auto; }
        .form-group { margin-bottom: 16px; }
        label { display: block; font-weight: 600; margin-bottom: 4px; }
        input, textarea {
            width: 100%;
            padding: 8px 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            box-sizing: border-box;
        }
        .counter { text-align: right; font-size: 13px; color: #666; margin-top: 2px; }
        .counter.over { color: #e74c3c; }
        .counter.under { color: #f39c12; }
    </style>
</head>
<body>
    <h2>发布文章</h2>
    <form>
        <div class="form-group">
            <label for="title">标题(5-50 字):</label>
            <input type="text" id="title" name="title" minlength="5" maxlength="50"
                   required oninput="updateCounter(this, 'title-counter')">
            <div class="counter" id="title-counter">0 / 50</div>
        </div>
        <div class="form-group">
            <label for="summary">摘要(20-200 字):</label>
            <textarea id="summary" name="summary" minlength="20" maxlength="200"
                      rows="3" oninput="updateCounter(this, 'summary-counter')"></textarea>
            <div class="counter" id="summary-counter">0 / 200</div>
        </div>
        <div class="form-group">
            <label for="content">正文(100-5000 字):</label>
            <textarea id="content" name="content" minlength="100" maxlength="5000"
                      rows="8" oninput="updateCounter(this, 'content-counter')"></textarea>
            <div class="counter" id="content-counter">0 / 5000</div>
        </div>
        <button type="submit">发布</button>
    </form>

    <script>
        function updateCounter(el, counterId) {
            const counter = document.getElementById(counterId);
            const len = el.value.length;
            const max = el.maxLength;
            const min = el.minLength;
            counter.textContent = `${len} / ${max}`;

            counter.className = 'counter';
            if (len > 0 && len < min) {
                counter.classList.add('under');
            } else if (len >= max * 0.9) {
                counter.classList.add('over');
            }
        }
    </script>
</body>
</html>

注意事项

maxlength 会截断输入

maxlength 是硬限制,用户无法输入超出限制的字符。如果粘贴的文本超长,超出部分会被截断。

minlength 不阻止输入

minlength 只在提交时验证,用户在输入过程中不会受到限制。需要在 UI 上给出提示。

与 required 配合

如果字段有 minlength 但没有 required,用户可以提交空值。需要强制填写时搭配 required

中文字符计算

minlength/maxlength 按字符数计算,一个中文字符算 1 个字符,与 JavaScript String.length 一致。

password 字段的 maxlength

对密码设置 maxlength 可能导致用户选择更长但更安全的密码时被截断。建议对密码只设 minlength 而不设 maxlength

最佳实践

  1. textarea 使用 maxlength:防止用户输入过长的内容
  2. 实时字数反馈:显示已输入/剩余/需要字符数
  3. 合理设置范围:minlength 不要太大,maxlength 不要太小
  4. password 慎用 maxlength:限制密码最大长度可能降低安全性
  5. 配合验证样式:使用 :too-short/:too-long 伪类提供视觉反馈

下一节

继续学习:disabled / readonly

参考链接