dom_dom0900_006

バリデーション付きフォームでは、inputやchangeイベントでリアルタイム検証を行い、無効時には( A )メソッドで送信を阻止する。また、アクセシビリティのためにエラーメッセージ領域に( B )=”assertive”を付け、画面リーダー通知を促す。

解答

A: preventDefault
B: aria-live

解説

submitハンドラでevent.preventDefault()により不正な送信を止める。動的に変わるエラー文はaria-liveリージョンに配置して支援技術へ即時読み上げを行う。

使用例(サンプルコード)

[ html ]

<form id="f">
  <input id="email" type="email" required>
  <button>送信</button>
</form>
<p id="err" aria-live="assertive"></p> <!-- (B) -->
<script>
f.addEventListener('submit', e=>{
  if(!email.checkValidity()){
    e.preventDefault(); // (A)
    err.textContent = 'メール形式が不正です';
  }
});
</script>