oninvalidイベント

定義と使用方法

送信可能な<input>要素が無効な場合、oninvalidイベントが発生します。

例えば、required属性が設定されており、フィールドが空の場合、入力フィールドは無効です(required属性は入力フィールドがフォームを提出する前に必ず入力される必要があることを指定しています)。

Instance

Example 1

If the input field is invalid, prompt some text:

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

実際に試してみる

More TIY examples are available at the bottom of the page.

Syntax

In HTML:

<element oninvalid="myScript">

実際に試してみる

In JavaScript:

object.oninvalid = function(){myScript};

実際に試してみる

In JavaScript, use the addEventListener() method:

object.addEventListener("invalid", myScript);

実際に試してみる

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

Technical details

Bubble: Not supported
Cancelable: Support
Event type: Event
Supported HTML tags: <input>
DOM version: Level 3 Events

Browser support

The numbers in the table indicate the first browser version that fully supports the event.

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

More examples

Example 2

If the input field contains fewer than 6 characters, prompt some text:

Name: <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>

実際に試してみる

Example 3

If the input field contains a number less than 2 or greater than 5, prompt some text:

Number: <input type="number" id="myInput" name="quantity" min="2" max="5" required>
<script>
document.getElementById("myInput").addEventListener("invalid", myFunction);
function myFunction() {
  alert("2から5の間の数字を選んでください。あなたが選んだのは: " + this.value);
}
</script>

実際に試してみる

関連ページ

JavaScript 教程:JavaScript フォーム