6

I've almost got my form validation working - I'm using Vee Validate 3 with Vue.js. Most of the examples of Vee Validate are for version 2, so I'm struggling a bit.

The issue I have is triggering the validation when submitting the form.

If I click the text field to focus on it first, then click submit, the validation fires and I see the error message.

If however, I don't click the text field first and just click the submit button, I don't see the error message.

How can I make this work without having to focus on the text field before I click submit?

Update

Weirdly, the console shows the error TypeError: this.validate is not a function in both cases - whether the validation works or not.

<ValidationProvider rules="required" v-slot="{ validate, errors }">
  <div>
    <input type="text" rules="required">
    <p id="error">{{ errors[0] }}</p>
  </div>
</ValidationProvider>

<script>
export default {
  methods: {
    async validateField() {
      const valid = await this.validate()
    }
  }
};
</script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Damian
  • 1,652
  • 4
  • 26
  • 44
  • I haven't use v3.0 but 1. Can you show whole code? 2. Did you check `ValidationObserver` ? https://logaretm.github.io/vee-validate/guide/validation-observer.html#validate-before-submit – Adam Orłowski Nov 03 '19 at 21:15
  • @Adam, I'll try the ValidationObserver - it looks promising. I'll report back here my findings. Thanks – Damian Nov 03 '19 at 21:30

2 Answers2

10

Adam pointed me in the right direction with the ValidationObserver.

This code works for me...

<ValidationObserver ref="observer" v-slot="{ invalid }" tag="form" @submit.prevent="submit()">
  <ValidationProvider rules="required" v-slot="{ errors }">
    <input type="text">
    <p id="error">{{ errors[0] }}</p>
  </ValidationProvider>
  <button @click="submit()">Submit>/button>
</ValidationObserver>

<script>
import { VslidationProvider, ValidationObserver } from 'vee-validate'
import { required } from 'vee-validate/dist/rules'

export default {
  methods: {
    async submit () {
      const valid = await this.$refs.observer.validate()
    }
  }
};
</script>
Damian
  • 1,652
  • 4
  • 26
  • 44
1

New way of doing it

<ValidationObserver v-slot="{ handleSubmit }">
  <ValidationProvider rules="required" v-slot="{ errors }">
    <input type="text">
    <p id="error">{{ errors[0] }}</p>
  </ValidationProvider>
  <button @click="handleSubmit(onSubmit)">Submit>/button>
</ValidationObserver>

<script>
import { VslidationProvider, ValidationObserver } from 'vee-validate'

export default {
  methods: {
    onSubmit() {
      // ...
    }
  }
};
</script>
quippe
  • 193
  • 2
  • 12
  • [official doc: validate-before-submit](https://vee-validate.logaretm.com/v3/guide/forms.html#validate-before-submit) – Rohim Chou Mar 14 '23 at 08:38