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

标签 javascript forms vue.js validation vuelidate

我正在使用 vuelidate 在表单上制作一些验证器以进行运输。目前我正在检查邮政编码的格式是否正确。不过,该字段取决于国家/地区字段(因为不同的国家/地区有不同的邮政编码格式。不过,我在访问 View 模型本身时遇到了问题,并且我没有在 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 上下文可能在某些情况下使用(不是在本例中)。但它显然不能用作箭头函数内的组件实例。

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

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

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

关于javascript - 如何使用 vuelidate 访问另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67875215/

相关文章:

javascript - setInterval 用于运行带有 if 语句的函数不起作用

Javascript 从 url 中删除符号 "amp;"

forms - 在 Twitter Bootstrap 中将标签包裹在输入控件周围

asp.net - 如何在 ASP.Net 中执行 <form method ="get"> 搜索表单?

vue.js - Vuex 中的异步/等待操作

javascript - 存储并返回到 Ember 路线

javascript - 如何解析无效的 json 字符串(带有十六进制值)

html - 如何通过css选择所有输入元素?

javascript - 无法在vue js中运行for循环

javascript - Vue 子组件属性不起作用