LoginSignup
2
1

More than 1 year has passed since last update.

Vue3.0+VeeValidate4.0で関数内の任意の場所でバリデーション実行する

Last updated at Posted at 2022-01-27

やることはタイトルの通りなんですが、公式のドキュメントは薄めだし、意外とググっても国内海外ともに情報が出てこなかったので、忘れないように残しておきます。

やりたいこと

submit時ではなく、ボタンのクリック時とかにFormレベルのバリデーションを噛ませたい

こんな感じで

export default defineComponent({
  setup() {
  },
  methods: {
    onClick() {
      // ここでバリデーションしてエラーしてたらreturnみたいなこと
    }
  }
})

どうやる?

他にもやり方はあるかもしれないですが、一旦こうやればやれた、というのを書いておきます。

template

Formのv-slotにvalidateを設定して、clickイベントで呼ぶ関数の引数に渡してやる

<template>
<Form v-slot="{ validate }" :validation-schema="schema">
  <!-- Fieldとかは必要なものを -->

  <button type="button" @click="onClick(validate)">
</Form>
</template>

script

<script>
import { Form, defineComponent } from 'vee-validate'

export default defineComponent({
  setup() {
    const schema = { 
      // 省略 
    }

    return {
      Form,
      schema,
    }
  },
  methods: {
    onClick(validate: any) {
      // ここでvalidation実行
      validate().then((result: any) => {
        if (result.valid) {
          // バリデーション突破
        } else {
          // バリデーション失敗
        }
      }
    }
  }
})
</script>
2
1
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
1