Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js VeeValidate how to prevent the submission of data until all the data is valid

My requirement is something like this.

  1. I have to input fields to validate user inputs.
  2. When user fills the fields and hit the submit button, before going to the submission I want to display all the error messages.
  3. Submission should happen if there is no errors in the user's data

This is my code.

<template>
  <div>
      <h1>Add Items</h1>
      Product Name : 
      <input
      type="text"
      name="product"
      v-model="product"
      v-validate="'required|alpha_dash'"
      >
      <span style="color:red;">{{errors.first('product')}}</span>
      <br>
      Product Price : 
      <input 
      type="number" 
      name="price" 
      v-model="price"
      v-validate="'required|min_value:100|max_value:500'"
      >
    <span style="color:red;">{{errors.first('product')}}</span>
      <br>
      <button @click="submit">Save</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      price: "",
      product: ""
    };
  },
  methods: {
    submit() {
      alert("On submit");
    }
  }
};
</script>

Now it only shows the first error {{errors.first('product')}} instead of this I want to display all the errors at once

and

this displays errors only you touch the input field. I want to display all the validation errors whether or not you touch the fields, I want to display all the errors when you hit the submit button.

like image 366
Pathum Kalhan Avatar asked May 02 '18 11:05

Pathum Kalhan


2 Answers

Sovalina's worked but the $validator.validateAll() was running AFTER the alert, meaning it wouldn't be validated first. I found this code and it worked well for me:

submit() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          alert('Form Submitted!');
          return;
        }

        alert('Correct them errors!');
      });
    }

from here: https://baianat.github.io/vee-validate/examples/

like image 99
artworkjpm Avatar answered Dec 01 '22 01:12

artworkjpm


In the latest vee-validate (version 3.0.5 as I write this), this has all changed. You need to wrap your entire form in a ValidationObserver component, with a ref (that you later access in your submit method) -

    <ValidationObserver ref="observer" v-slot="{ invalid }"  @submit.prevent="submit()">
        <ValidationProvider ...
            <input... etc

Your submit method needs to look like this:

async submit () {
  const isValid = await this.$refs.observer.validate()
  if (isValid) {
    // data is valid - post your form data
  } else {
    alert('Data isn't valid')
  }
}

There are a number of ways you can import the ValidationProvider component - this is regular vue stuff... here is a link to the doc:

https://logaretm.github.io/vee-validate/api/validation-observer.html

like image 35
Rob Avatar answered Dec 01 '22 01:12

Rob