LoginSignup
9
5

More than 5 years have passed since last update.

【Vee-Validate】個々のエラーだけをリセットする方法

Last updated at Posted at 2018-07-28

エラーオブジェクト (vueインスタンス内) にアクセスするには?

入力が変更されるたびに、バリデーターは検証のリストを順番に実行し、
入力内容が検証に失敗した場合エラーオブジェクトに格納します。

エラーオブジェクトには以下でアクセスできます✅

this.$validator.errorBag
// or
this.errors

エラーをリセットする方法

エラーをリセットする場合、以下のようにreset()を呼び出します。

this.$validator.reset()

※ドキュメントによると$validator.clean()は推奨されていません

しかし、$validator.reset()は全てのフィールドがリセットされてしまいます😂
個々のフィールドだけをリセットする場合は、個々に対してエラーを取り除く必要があります。

個々のエラーだけをリセット

現在のところ(v2.0.0)では、個々のエラーをリセットするサポートはありません😢

回避策としてFieldクラスのインスタンスである$validator.fields.itemsをループして
対象のフィールドでreset()を呼び出す?😧

this.$validator.fields.items.forEach(each => {
  if (each.el.name === '対象のフィールド') {
    each.reset()
  }
})

しかし、上記ではreset()を呼び出すと、フラグとクラスはリセットされますが、
エラーオブジェクトにあるエラー自体は取り除かれません😷💦


const matchOptions = {
  id: any, // if you have the id, otherwise its optional
  name: string, // optional
  scope: string // optional
}

const field = this.$validator.fields.find(matchOptions)
field.reset()
this.$validator.errors.remove(field.name, field.scope)

エラー自体を取り除く場合、$validator.errors.removeを使用する必要があります✋
もっとスマートなやり方としては、上記のように対象のフィールドを検索して、
その対象フィールドにreset()errors.remove()を実行する方法です✌️

参考

I know its not in the docs, We will fix that with the new docs. I just pushed an enhancement for this issue, should be up with the next release soon.

今後のリリースには、この機能が追加がされるみたいですね🙏

ドキュメントはこちら
VeeValidate

参考

9
5
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
9
5