7

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>

1 Answer 1

11

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Invalid prop: type check failed for prop "rules". Expected Array, got String. This is the error I am getting now
oops, yeah, passed empty string, pass an empty array instead :rules="notRequired ? 'nameRules' : []"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.