Peristiwa oninvalid

Pengartian dan penggunaan

Peristiwa oninvalid terjadi apabila elemen <input> yang boleh disubmit tak sah.

contoh, jika diatur sifat required, dan bidang kosong, isian input tak sah (sifat required menentukan isian input mesti diisi sebelum menghantar borang).

Example

Example 1

If the input field is invalid, display some text:

<input type="text" oninvalid="alert('You must fill out the form!');" required>

Cuba sendiri

More TIY examples are at the bottom of the page.

Syntax

In HTML:

<element oninvalid="myScript">

Cuba sendiri

In JavaScript:

object.oninvalid = function(){myScript};

Cuba sendiri

In JavaScript, use the addEventListener() method:

object.addEventListener("invalid", myScript);

Cuba sendiri

Note:Internet Explorer 8 or earlier versions do not support addEventListener() Method.

Technical Details

Bubble: Not Supported
Cancelable: Supported
Event Type: Event
Supported HTML Tags: <input>
DOM Version: Level 3 Events

Browser Support

Bilangan di dalam tabel menunjukkan versi perekap pertama yang mendukung peristiwa ini sepenuhnya.

Event Chrome IE Firefox Safari Opera
oninvalid Supported 10.0 Supported Supported Supported

More examples

Contoh 2

Jika medan input mengandungi kurang daripada 6 aksara, tampilkan teks beberapa:

Nama: <input type="text" id="myInput" name="fname" pattern=".{6,}" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
  alert("Must contain 6 or more characters");
}
</script>

Cuba sendiri

Contoh 3

Jika medan input mengandungi nombor kurang daripada 2 atau lebih daripada 5, tampilkan teks beberapa:

Bilangan: <input type="number" id="myInput" name="quantity" min="2" max="5" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
  alert("Anda mesti memilih nombor antara 2 dan 5. Pilihan anda: " + this.value);
}
</script>

Cuba sendiri

Laman yang berkaitan

Panduan JavaScript: Borang JavaScript