JavaScript Validation API

วิธีและคุณสมบัติของ DOM ที่ใช้ตรวจสอบข้อกำหนด

วิธี

วิธี 描述
checkValidity() กลับค่า true ถ้า input มีข้อมูลที่ถูกต้อง
setCustomValidity() ตั้งค่ารายการ validityMessage ของ input

屬性

屬性 描述
validity มีค่าของประกายที่เกี่ยวข้องกับการตรวจสอบความถูกต้องของ input
validationMessage มีข้อความที่บราวน์เซอร์จะแสดงเมื่อการตรวจสอบมีค่าเป็น false
willValidate บอกว่าจะตรวจสอบ input หรือไม่

ตัวอย่าง - วิธี checkValidity()

ถ้าฟิลด์รับข้อมูลผิดปกติ จะแสดงข้อความเตือน:

<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
  const inpObj = document.getElementById("id1");
  if (!inpObj.checkValidity()) {
    document.getElementById("demo").innerHTML = inpObj.validationMessage;
  }
}
</script>

ลองด้วยตัวเอง

有效性屬性

input 元素的有效性屬性包含許多與數據有效性相關的屬性:

屬性 描述
customError 如果設置了自定義的有效性消息,則設置為 true。
patternMismatch 如果元素的值與其 pattern 屬性不匹配,則設置為 true。
rangeOverflow 如果元素的值大於其 max 屬性,則設置為 true。
rangeUnderflow 如果元素的值小於其 min 屬性,則設置為 true。
stepMismatch 如果元素的值根據其 step 屬性無效,則設置為 true。
tooLong 如果元素的值超過其 maxLength 屬性,則設置為 true。
typeMismatch 如果元素的值根據其 type 屬性無效,則設置為 true。
valueMissing 如果元素(帶有 required 屬性)沒有值,則設置為 true。
valid 如果元素的值有效,則設置為 true。

示例

rangeOverflow 屬性

如果 input 字段中的數字大於 100(input 的 max 属性),則顯示一條消息:

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
  let text = "Value OK";
  if (document.getElementById("id1").validity.rangeOverflow) {
    text = "Value too large";
  }
}
</script>

ลองด้วยตัวเอง

rangeUnderflow 屬性

如果 input 字段中的數字大於 100(input 的 max 属性),則顯示一條消息:

<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
  let text = = "Value OK";
  if (document.getElementById("id1").validity.rangeUnderflow) {
    text = "Value too small";
  }
}
</script>

ลองด้วยตัวเอง