ValidityState: tooShort 屬性

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2018 年 12 月起,所有瀏覽器均支援此功能。

ValidityState 介面的只讀 tooShort 屬性指示 ValidityState 介面的只讀 tooShort 屬性表示,經過使用者編輯後,<input><button><select><output><fieldset><textarea> 元素的值是否小於元素 minlength 屬性設定的最小程式碼單元長度。

如果 ValidityState 不符合約束,則為 true 的布林值。

示例

輸入值過短

下面的示例檢查一個 文字輸入元素 的有效性。使用 minlength 屬性 添加了一個約束,因此輸入需要至少包含 4 個字元。如果使用者輸入的字串太短,該元素將驗證失敗,並應用與 :invalid CSS 偽類匹配的樣式。

css
input:invalid {
  outline: red solid 3px;
}
html
<pre id="log">Validation logged here...</pre>
<input type="text" id="userText" minlength="4" />
js
const userInput = document.getElementById("userText");
const logElement = document.getElementById("log");

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

userInput.addEventListener("input", () => {
  userInput.reportValidity();
  if (userInput.validity.tooShort) {
    log("Not enough characters entered.");
  } else {
    log("Input is valid…");
  }
});

規範

規範
HTML
# dom-validitystate-tooshort-dev

瀏覽器相容性

另見