HTMLTextAreaElement: setCustomValidity() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

setCustomValidity() 方法是 HTMLTextAreaElement 接口的一部分,用于设置 <textarea> 元素的自定义有效性消息。使用空字符串表示该元素没有自定义有效性错误。

语法

js
setCustomValidity(string)

参数

string

包含错误消息的字符串。空字符串会移除任何自定义有效性错误。

返回值

无(undefined)。

示例

在此示例中,如果 <textarea> 未通过约束验证,我们将根据验证失败的约束提供自定义错误。如果值为有效,我们将自定义错误设置为一个空字符串。

js
const comment = document.getElementById("comment");
if (comment.validity.valueMissing) {
  comment.setCustomValidity("We can't submit a blank comment!");
} else if (comment.validity.tooShort) {
  comment.setCustomValidity("Tell us more! Your comment is too short.");
} else if (comment.validity.tooLong) {
  comment.setCustomValidity(
    "Loquacious much? Keep it to under 800 characters!",
  );
} else {
  comment.setCustomValidity("");
}

规范

规范
HTML
# dom-cva-setcustomvalidity-dev

浏览器兼容性

另见