【问题标题】:How do I dynamically set validations fields in vuelidate如何在 vuelidate 中动态设置验证字段
【发布时间】:2018-04-25 08:04:02
【问题描述】:

我正在使用带有 vuelidate 库的 VueJS2。我可以根据验证对象验证字段。验证将在计算时间内执行。但我的验证对象是固定的,而不是动态的。我有一些字段将根据选择隐藏。

import { validationMixin } from 'vuelidate'
import { required, maxLength, email } from 'vuelidate/lib/validators'

export default {
mixins: [validationMixin],
validations: {
  company_name: { required },
  company_position_title: { required }
},
methods: {
  submit(){
    this.$v.touch();
    if(this.$v.$invalid == false){ 
      // All validation fields success
    }
  }
}
}

HTML

<v-select
  label="Who are you?"
  v-model="select" // can be 'company' or 'others'
  :items="items"
  :error-messages="selectErrors"
  @change="$v.select.$touch();resetInfoFields();"
  @blur="$v.select.$touch()"
  required
></v-select>

<v-text-field
  label="Company Name"
  v-model="company_name"
  :error-messages="companyNameErrors"
  :counter="150"
  @input="$v.companyName.$touch()"
  @blur="$v.companyName.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-text-field
  label="Company Position Title"
  v-model="company_position_title"
  :error-messages="companyPositionErrors"
  :counter="150"
  @input="$v.companyPosition.$touch()"
  @blur="$v.companyPosition.$touch()"
  v-show="select == 'Company'"
></v-text-field>

<v-btn @click="submit">submit</v-btn>

问题

当我选择“其他”选项并单击提交时,this.$v.$invalid 仍然为真。它应该是 false,因为不需要验证字段。 当我选择“公司”时,必须要求并验证这两个字段。

【问题讨论】:

    标签: validation vue.js vuejs2 vuetify.js vuelidate


    【解决方案1】:

    您需要一个动态验证架构

    validations () {
      if (!this.select === 'company') {
        return {
          company_name: { required },
          company_position_title: { required }
        }
      }
    }
    

    更多信息:Dynamic validation schema

    【讨论】:

    • 说它的 $dirty of undefined
    • 您不能在对象声明中使用 if 语句。
    【解决方案2】:

    另一种方法是使用 requiredIf

    itemtocheck: {
      requiredIf: requiredIf(function () {
        return this.myitem !== 'somevalue'
      }),
      minLength: minLength(2) },
    

    【讨论】:

    • minLength 仍然会被应用,所以它不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2012-07-14
    • 2019-03-23
    相关资源
    最近更新 更多