大网数据广告活动
Web 标准与前端开发

ValidityState: tooLong property

· 52CE 我爱测

The read-only **`tooLong`** property of the `ValidityState` interface indicates if the value of an input or textarea, after having been edited by the user, exceeds the maximum code-unit length established by the element's `maxlength` attribute.

HTML DOM

The read-only tooLong property of the ValidityState interface indicates if the value of an input or textarea, after having been edited by the user, exceeds the maximum code-unit length established by the element's maxlength attribute.

Value

A boolean that is true if the ValidityState does not conform to the constraints.

Examples

Textarea with too long character count

The following example checks the validity of a textarea element. A constraint has been added using the maxlength attribute so the textarea expects a maximum of 10 characters. If there are too many characters in the textarea (which is true below), the element fails constraint validation, and the styles matching :invalid CSS pseudo-class are applied.

When editing the textarea, the browser will not allow the user to add characters that would fail constraint validation of maximum character count, so at first, only deleting characters is allowed. Newline characters are normalized and count as a single character in the maximum length calculation.

textarea:invalid {
  outline: red solid 3px;
}
body {
  margin: 0.5rem;
}
textarea {
  width: 75%;
}
pre {
  padding: 1rem;
  height: 2rem;
  background-color: lightgrey;
  outline: 1px solid grey;
}
<pre id="log">Validation logged here...</pre>
<textarea name="story" id="userText" maxlength="10" rows="5">
It was a dark and


stormy night...
</textarea>
const userInput = document.getElementById("userText");
const logElement = document.getElementById("log");

function log(text) {
  logElement.innerText = text;
}

userInput.addEventListener("input", () => {
  userInput.reportValidity();
  if (userInput.validity.tooLong) {
    log("Too many characters in the textarea.");
  } else {
    log("Input is valid…");
  }
});

textarea_with_too_long_character_count

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。