'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>
Solution 1:[1]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |