2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vue.jsでHTML5 Form validationの利用

Last updated at Posted at 2017-06-29

目的

vue.jsでSPAページの構築時、submitせずにHTML5 Form validationを利用

方法

<form id="form" @submit.prevent="">
  <input type="text" required />
  <button @click="update" />
</form>
  • buttonのclick eventは、formタグに伝播させる
  • formタグでは、click eventは受け付けるが、submit eventはpreventで処理させない
    • formタグでのclick event受付時にHTML5 Form validationが実施される
    • validationの実行結果に問題なければ、formタグでsubmit eventが発行されるのでprevent
export default {
  methods: {
    update () {
      const form = document.getElementById('form');
      if (!form.checkValidity()) return;
      // 以降、省略
      // API request && 画面遷移処理 etc..
    }
  }
}
  • checkValidity()の結果に従って処理の実施可否を判定

備考

  • Form上でのEnter Key実行は、buttonタグのclick eventと解釈され、@clickの処理が実施される
  • Safari / Chromeでの動作確認はしたが、それ以外のブラウザでの動作検証は未達
2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?