简体   繁体   中英

Problems with validation before submit

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>

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM