如何使用 vuelidate 访问另一个字段

How do I access another field using vuelidate

我正在使用 vuelidate 在运输表格上制作一些验证器。目前我正在检查 postalCode 的格式是否正确。这个字段取决于国家字段(因为不同的国家有不同的邮政编码格式。我在访问视图模型本身时遇到了问题,而且我没有在 vuelidates 文档中得到解释。

目前我正在使用以下经过编辑的代码:

import Vue from 'vue';
import {validationMixin} from 'vuelidate';
import {required} from 'vuelidate/lib/validators';
import {getEuMembers} from 'is-eu-member';
import countries from 'i18n-iso-countries';
import postalCodes from 'postal-codes-js';
new Vue({
  el: '#app',
  mixins: [shoppingBagMixin, validationMixin],
  data: {
    form: {
      country: {},
      postalCode: '',
      // more data...
    },
  },
  validations: {
    form: {
      $each: {required},
      country: {
      },
      postalCode: {
// ----------- The following 3 lines are problematic ----------
        validPostalCode: (value) => { 
          if (!this.country || !this.country.code) return false; 
          return postalCodes.validate(this.country.code, value);
        },
      },
    },
  },
methods: {
    euCountries: euCountries,
    async onSubmit(event) {
      this.$v.$touch();
      if (this.$v.$invalid) {
        return false; // TODO: Show error
      }

      // Sending data using fetch()

      return false;
    },
  },
});

/**
 * Returns a list of EU country codes and translated names
 * @param {String} lang Language to translate the country name to.
 * Needs to be a code such as 'nl' or 'en'
 * @return {Array} Array of {code: ISOCode, name: name} objects
 */
function euCountries(lang) {
  countries.registerLocale(require(`i18n-iso-countries/langs/${lang}.json`));
  return getEuMembers().map((ISOCode) => {
    const name = countries.getName(ISOCode, lang, {});
    return {code: ISOCode, name: name};
  });
}

为完整起见,摘录以下形式:

<fieldset>
  <legend>Adres:</legend>
  <label for="country">Land:</label>
  <select id="country" name="country" v-model="form.country" type="text">
    <option v-once v-for="country in euCountries('nl')" :value="country">{{country.name}}</option>
  </select>
  <label for="postalCode">Postcode:</label>
  <input id="postalCode" name="postalCode" v-model="form.postalCode" type="text">
</fieldset>

this context 可能在某些情况下被使用(不是在这一个)。但它显然不能作为箭头函数中的组件实例使用。

the documentation所示,组件实例在自定义验证器中作为第二个参数可用:

validPostalCode: (value, vm) => { 
  // vm.country 
  ...

这适用于 Vuelidate 0.x,但不适用于 2.x 和合成 API。

this 将引用 vm 如果这样使用(注意 validations 现在是一个函数):

data () {
  return {
    myProperty: 'my-property',
    otherProperty: 'other-property'
  }
},

validations () {
  return {
    myProperty: {
      sameAs: myCustomValidator(this.otherProperty)
    }
  }
}