Skip to content

required_if is only working on first submit #4868

@pratiklabh

Description

@pratiklabh

when i try to submit paymentMode as online banking and not selecting bank then it shows validation error mentioning bank is required
then i enter a bank and submit
and (without refreshing the page) again if i submit online banking without selecting bank then validation is not working, data can be submitted

Transaction Information Form

  <!-- Bank Name Dropdown Column -->
  <Column header="Bank Name">
    <template #body="{ data }">
      <Field name="bank" v-slot="{ field }" :rules="requiredIfOnlineBanking(data.paymentMode)">
        <Select
            v-model="data.bank"
            v-bind="field"
            :options="banks"
            optionLabel="label"
            optionValue="value"
            placeholder="Select Bank"
            class="w-full"
            :disabled="data.paymentMode !== 'Online Banking'"
        />
        <ErrorMessage name="bank" class="error" />
      </Field>
    </template>
  </Column>
</DataTable>

<Button type="submit" class="submit-button">
  Submit
</Button>
<script setup> import { ref } from 'vue'; import { ErrorMessage, Field, Form } from 'vee-validate'; import Select from 'primevue/select'; import Button from 'primevue/button'; import DataTable from 'primevue/datatable'; import Column from 'primevue/column'; import { defineRule } from 'vee-validate'; import { required } from '@vee-validate/rules'; defineRule('required', required); defineRule('required_if', (value, [compareField, compareValue], ctx) => { if (ctx.form[compareField] === compareValue) { return !!value || 'This field is required when payment mode is Online Banking.'; } return true; }); // Function to determine required rule for bank field const requiredIfOnlineBanking = (paymentMode) => { return paymentMode === 'Online Banking' ? 'required' : ''; }; // Transaction data const transactions = ref([{ id: 1, paymentMode: '', bank: '' }]); // Select options for payment modes and banks const paymentModes = ref([ { label: 'Cash', value: 'Cash' }, { label: 'Online Banking', value: 'Online Banking' }, ]); const banks = ref([ { label: 'Nabil', value: 'Nabil' }, { label: 'NMB', value: 'NMB' }, { label: 'NIC ASIA', value: 'NIC ASIA' }, ]); // Function to reset bank field when payment mode changes const resetBankField = (data) => { if (data.paymentMode !== 'Online Banking') { data.bank = ''; // Clear the bank field } }; // Form submission handler const handleSubmit = () => { alert('Form submitted successfully!'); console.log('Submitted Data:', JSON.stringify(transactions.value, null, 2)); }; </script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions