如何在vuelidate中动态设置验证字段

Abe*_*bel 4 validation vue.js vuejs2 vuetify.js vuelidate

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

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

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

问题

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

Mas*_*ske 5

您需要一个动态验证模式

validations () {
  return {
    if (!this.select === 'company') {
      company_name: { required },
      company_position_title: { required }
    }
    // other validations
  }
}
Run Code Online (Sandbox Code Playgroud)

更多信息:动态验证架构


小智 5

另一种方法是使用 requiredIf

itemtocheck: {
  requiredIf: requiredIf(function () {
    return this.myitem !== 'somevalue'
  }),
  minLength: minLength(2) },
Run Code Online (Sandbox Code Playgroud)