简体   繁体   中英

How to set conditional rules and required fields in vue?

I am trying to make few fields conditionally required. But I am not able to make it work. I have set a data field notRequired: false and based on that I am using it in the fields as :required="!notRequired" to make those fields as not required because in some cases I need those fields as required and in some cases I don't because of which I trying to set that conditionally. The issue is the error message still appears because of the rules which are added to the fields. Is there a way to make the rules conditional too?

<template>
 <v-text-field
  label='Agency Name'
  v-model='agency.name'
  :rules='nameRules'
  :required="!notRequired"
  required>
 </v-text-field>
 <v-text-field
  label='Agency Code'
  :rules='codeRules'
  :required="!notRequired"
  v-model='agency.code'>
 </v-text-field>
 <v-text-field
  label='Agency location'
  :rules='locationRules'
  :required="notRequired"
  v-model='agency.location'>
 </v-text-field>
</template>

<script>
 export default {
  data: function () {
    return {
      notRequired: false,
      agency: {
        name: '',
        code: '',
        location: '',
      }
      nameRules: [
        value => !!value || 'Please enter name'
      ],
      codeRules: [
        value => !!value || 'Please enter code'
      ],
      locationRules: [
        value => !!value || 'Please enter location'
      ],
    }
  }
 }
</script>

You can use the ternary operator to conditionally add rules, depending on the value of notRequired :

 <v-text-field
   label="Agency Name"
   v-model="agency.name"
   :rules="notRequired ? 'nameRules' : []" <!-- HERE -->
   :required="!notRequired">
 </v-text-field>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM