【问题标题】:How do I access another field using vuelidate如何使用 vuelidate 访问另一个字段
【发布时间】:2021-06-07 16:15:41
【问题描述】:

我正在使用 vuelidate 为发货表单制作一些验证器。目前我正在检查邮政编码的格式是否正确。不过,此字段取决于国家/地区字段(因为不同的国家/地区有不同的邮政编码格式。不过,我在访问视图模型本身时遇到了问题,而且我在 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};
  });
}

为了完整起见,sn-p 的形式为:

<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>

【问题讨论】:

    标签: javascript forms vue.js validation vuelidate


    【解决方案1】:

    this 在某些情况下可能正在使用上下文(不是在这个情况下)。但它显然不能用作箭头函数内的组件实例。

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

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

    这适用于 Vuelidate 0.x,与 2.x 和组合 API 的工作方式不同。

    【讨论】:

      猜你喜欢
      • 2018-06-14
      • 2020-04-21
      • 2022-11-20
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多