source

vuelidate에서 검증 필드를 동적으로 설정하려면 어떻게 해야 합니까?

goodcode 2022. 8. 19. 20:48
반응형

vuelidate에서 검증 필드를 동적으로 설정하려면 어떻게 해야 합니까?

VueJs2와 vuelidate 라이브러리를 사용하고 있습니다.검증 개체를 기반으로 필드를 검증할 수 있습니다.검증은 계산된 시간 동안 실행됩니다.그러나 My Validations 객체는 동적 대신 고정됩니다.선택 내용에 따라 숨길 필드가 있습니다.

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전히사사 사사사다다거짓'company두 및 회사'를 선택한 경우 두 개의 필드가 필수이고 검증되어야 합니다.

동적 검증 스키마가 필요합니다.

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

상세 정보: 동적 검증 스키마

또 다른 방법은 필요한 것을 사용하는 것입니다.한다면

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

언급URL : https://stackoverflow.com/questions/47250791/how-do-i-dynamically-set-validations-fields-in-vuelidate

반응형