0

I'm trying to get an example from the VeeValidate docs to work. It can be found here. I'm clearly missing something but I don't know what.

My form is always valid, even though I'm not adding any text to the inputs. Do I need to customise the required rule somehow? CodeSandbox

<template>
  <ValidationObserver ref="observer" v-slot="{ invalid }" tag="form" @submit.prevent="submit()">
    <input type="text" rules="required">
    <br>
    <input type="text" rules="required">
    <br>
    <button :disabled="invalid">Submit</button>
  </ValidationObserver>
</template>

<script>
import { ValidationObserver } from "vee-validate";

export default {
  components: {
    ValidationObserver
  },
  methods: {
    async submit() {
      const isValid = await this.$refs.observer.validate();

      console.log("Form is valid", isValid);

      if (!isValid) {
        // ABORT!!
      }

      //  ship it
    }
  }
};
</script>

João
  • 449
  • 4
  • 18
Mala
  • 115
  • 3
  • 9
  • Hi, your question should include all the relevant code directly. Good to have the link to the Code Sandbox, but the goal is to also have your question "stand alone" if the link goes bad. – Ryley Nov 27 '19 at 00:01
  • 1
    Hi, thanks for pointing that out. I updated my question with the code. – Mala Nov 27 '19 at 14:21

1 Answers1

1

Each input needs to be wrapped in a ValidationProvider. Change this:

<input type="text" rules="required">

To this:

<ValidationProvider rules="required">
    <input type="text" rules="required" v-model="something">
</ValidationProvider>

Additionally, somewhere, you need to actually define the rules you want to use, so at the top of the file I put this:

import { ValidationObserver, ValidationProvider, extend } from "vee-validate";
import { required } from 'vee-validate/dist/rules';

extend('required',required);

Working copy of your Code Sandbox (I also updated vee-validate and vue to the latest versions): https://codesandbox.io/s/vue-template-dj9jn

To actually get the behaviour mentioned in the example, instead of using the invalid flag of ValidationObserver, try using the handleSubmit method like so:

<ValidationObserver tag="form" v-slot="{handleSubmit}" @submit.prevent>
  ... 
  <button @click="handleSubmit(submit)">Submit</button>

And your submit function would look like this:

submit() {
    //anything you do here will only be called when the form is valid
}
Ryley
  • 21,046
  • 2
  • 67
  • 81
  • Thanks, I'll try with `ValidationProvider `. I can't get your CodeSandbox example to work though, I get error `_vm.handleSubmit is not a function`. – Mala Nov 27 '19 at 14:24
  • I updated the sandbox and edited the answer... Now the handleSubmit call is on the button inside the form rather than directly on the ValidationObserver – Ryley Nov 27 '19 at 16:18