VueJS + VeeValidator + Multiple fields

Versions:
  • VueJs: 2.2.2
  • Vee-Validate: 2.0.0-beta.25

Description:

I'm wondering if there is a way to have a unique validator for multiple fields?

Typically an address form with 1 input on the street, 1 for a number and 1 for a city

I want to do a check for a combination of all elements.

I have read the documentation but cannot find an example that could help me.

+3


source to share


1 answer


You can apply a custom validator to a custom component containing all the fields you want to validate together. For example, you can create a component location

(using location

instead address

because it address

is an HTML5 element and you cannot name a Vue component the same as an existing HTML element).

Vue.component("location", {
  props:["value"],
  template: "#location-template",
  data(){
    return {
      location: this.value
    }
  },
  methods:{
    update(){
      this.$emit('input', Object.assign({}, this.location))
    }
  },
})

      

Then you can create a validator for this component.

const locationValidator = {
  currentLocation: null,
  getMessage(field, args) {
    if (!this.currentLocation.street)
      return "Location requires a street";
    if (!this.currentLocation.street_number)
      return "Location requires a street_number";
    if (!this.currentLocation.city)
      return "Location requires a city";
  },
  validate(location, args) {
    this.currentLocation = location;

    if (!location.street || !location.street_number || !location.city)
      return false;

    return true
  }
};

      

Finally, you can bundle this into your Vue.



new Vue({
  el:"#app",
  data:{
    loc: {}
  },
  created(){
    this.$validator.extend("location", locationValidator)
  }
})

      

And your Vue template

<span v-show="errors.has('location')" style="color:red">{{ errors.first('location') }}</span>
<location v-validate="'location'" v-model="loc" data-vv-name="location"></location>

      

Here's an example .

+2


source







All Articles