HTML 表单属性

除了 typename,表单控件还有很多属性来约束输入、优化体验。

约束与验证

html
<!-- 必填 -->
<input type="text" name="username" required>

<!-- 最小/最大长度 -->
<input type="text" name="code" minlength="6" maxlength="12">

<!-- 最小/最大值(数字和日期类型) -->
<input type="number" name="age" min="18" max="65">

<!-- 正则模式 -->
<input type="text" name="zip" pattern="[0-9]{6}" title="请输入6位数字邮编">

<!-- 步进(数字类型) -->
<input type="number" name="quantity" step="0.5">

提示与占位

html
<!-- 占位文字(输入前显示,输入后消失) -->
<input type="text" name="search" placeholder="输入关键词搜索...">

<!-- 工具提示(鼠标悬停时显示) -->
<input type="text" name="username" title="请输入 4-20 位字符">

placeholder 不是 label 的替代品!它的对比度通常较低,输入后就会消失,用户可能忘了要填什么。始终配合 <label> 使用。

自动行为

html
<!-- 自动聚焦 -->
<input type="text" name="username" autofocus>

<!-- 自动填充 -->
<input type="text" name="name" autocomplete="name">
<input type="email" name="email" autocomplete="email">
<input type="tel" name="phone" autocomplete="tel">

<!-- 禁用自动填充 -->
<input type="text" name="captcha" autocomplete="off">

<!-- 拼写检查 -->
<textarea name="comment" spellcheck="true"></textarea>
<!-- spellcheck 也可设为 false 禁用 -->

其他常用属性

html
<!-- 输入建议列表 -->
<input type="text" name="country" list="countries">
<datalist id="countries">
  <option value="中国"><option value="美国"><option value="日本">
</datalist>

<!-- 多选(文件、email 等) -->
<input type="file" name="photos" multiple>
<input type="email" name="recipients" multiple>

<!-- 接受文件类型 -->
<input type="file" name="doc" accept=".pdf,.doc,.docx">
<input type="file" name="photo" accept="image/*">

<!-- 尺寸(仅用于视觉提示,不替代验证) -->
<input type="text" name="code" size="6" maxlength="6">

<!-- 输入模式(移动端弹出对应键盘) -->
<input type="text" name="amount" inputmode="numeric">
<!-- inputmode 可选: text, numeric, decimal, tel, email, url, search -->

inputmode 属性控制移动端虚拟键盘的类型。它与 type 不同——type="text" + inputmode="numeric" 会弹出数字键盘但输入的值仍是字符串,这适用于金额、邮编等场景。

表单级属性

html
<form action="/submit" method="post"
      autocomplete="on"
      novalidate
      target="_blank">
</form>
  • autocomplete="on" — 开启所有字段的自动填充(继承到子控件)
  • novalidate — 跳过浏览器原生验证(验证逻辑由 JS 接管时使用)
  • target — 提交后结果在哪里显示(与 <a> 的 target 相同)