VueJS + VeeValidator +多个字段

Gil*_*art 4 vue.js

版本:

  • VueJs:2.2.2
  • Vee验证:2.0.0-beta.25

描述:

我想知道是否有办法为多个字段提供唯一的验证器?

通常,地址表单带有1个输入,代表街道,1个代表数字,1个代表城市

我想对所有元素的组合进行验证。

我已经阅读了文档,但找不到能为我提供帮助的示例。

Ber*_*ert 5

您可以将自定义验证器应用于包含要一起验证的所有字段的自定义组件。例如,您可以构建一个location组件(使用location代替,address因为addressHTML5元素是HTML5元素,而不能使用与现有HTML元素相同的名称命名Vue组件)。

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

然后,您可以为该组件构建一个验证器。

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
  }
};
Run Code Online (Sandbox Code Playgroud)

最后,您可以在Vue中将其组合在一起。

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

还有你的Vue模板

<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>
Run Code Online (Sandbox Code Playgroud)

这是一个例子