[Vuejs]-Vee validate across multiple fields

0👍

First, there is some errors in your snippet:
You create a new vee-validate rule called total_cost but you don’t bind it to the v-validate directive (instead you try to pass a computed property).
Change your inputs with v-validate="'total_cost'" (note that total_cost is binded as a string)


Now you can use the any method provided by Vee-validate (source) to return a global error message:

Vue.use(VeeValidate)

new Vue({
  el: "#app",
  data () {
    return { v1: 0, v2: 0, v3: 0, v4: 0, v5: 0 }
  },
  computed: {
    errorMsg() {
      if (this.errors.any()) {
      	return 'At least one value must be supplied'
      }
    }
  },
  created: function () {
    this.$validator.extend('total_cost', {
      vTotalCost:0,
      getMessage: function (field) { 
        return 'At least one value must be supplied'; 
      },
      validate: function (value) {
        this.vTotalCost = value;
        return this.vTotalCost != 0;                
      }
    })
  }
})
.has-error {
  color: red;
  font-size: 12px;
}
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<script src="https://unpkg.com/vee-validate@2.0.0-beta.25"></script>
<div id="app">
  <input type="text" v-model.number="v1" data-vv-as="v1" v-validate="'total_cost'" name="v1"/>
  <input type="text" v-model.number="v2" data-vv-as="v2" v-validate="'total_cost'" name="v2"/>
  <input type="text" v-model.number="v3" data-vv-as="v3" v-validate="'total_cost'" name="v3"/>
  <input type="text" v-model.number="v4" data-vv-as="v4" v-validate="'total_cost'" name="v4"/>
  <input type="text" v-model.number="v5" data-vv-as="v5" v-validate="'total_cost'" name="v5"/>
  <p class="has-error">{{ errorMsg }}</p>
</div>

Leave a comment