7
3

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.

VeeValidateで最初のフィールドがinvalidになってしまう問題の対処法

Last updated at Posted at 2017-09-25

TL;DR

created() {
  this.$validator.reset();
},

概要

VeeValidateを使ってバリデーションを書いていると、フォームの最初のinput要素がはじめからinvalidになっていることに気づくでしょう。

たとえば、下記のようなコンポーネントとテンプレートがあるとします。

export default {
  data() {
    return {
      field1: '',
      field2: '',
    };
  }
}
<form action="">
  <input type="text" name="field1" v-model="field1" v-validate="'required'">
  <input type="text" name="field2" v-model="field2" v-validate="'required'">
</form>

このとき、 errors.has('field1')false を返す状態ですが、field1の aria-invalid 属性は true になっているはずです。これはなぜかというと、最初のフィールドの flags.invalidtrue になっているからです。

実際に動かして確認したい方は https://jsfiddle.net/ft1z8aqs/2/ を参照してください。

最初の要素の flags.invalidtrue になるのは、ブラウザのオートフォーカスによって最初の要素のfocusイベントが発生して、バリデーションが行われるからだと思われます。

この挙動の影響で、 aria-invalid 属性や .invalid というCSSクラスに頼ったバリデーション状態のスタイリングが難しくなっています。

VeeValidateのバグなのか仕様なのかは不明です。

対処方法

冒頭にも記述したとおり、コンポーネントのcreatedのフックで、バリデーションをリセットすればOKです。

created() {
  this.$validator.reset();
},

jsfiddleにも、修正前後の状態を載せているので、実際に動かしてみてください。

修正前:初期表示でfield1の aria-invalid がtrueになっている
https://jsfiddle.net/ft1z8aqs/2/

修正後:初期表示でfield1の aria-invalid がfalseになっている
https://jsfiddle.net/ft1z8aqs/3/

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?