vue.jsvuetify.jsv-data-table

v-data-table checked validate v-text-field type number


How do I validate a number input field inside v-data-table? I want to set required only on checked row.

enter

here's my code

<v-data-table
  v-model="selected"
  :headers="dataHeaders"
  :items="mealTimes"
  show-select
  @click:row="setTime"
>
  <template #[`item.data-table-select`]="{ item, isSelected }">
    <v-simple-checkbox
      :value="isSelected"
      color="primary"
      :ripple="false"
      @input="setSelected(item, isSelected)"
    />
  </template>
  <template #[`item.weight`]="{ item }">
      <div class="w-100">
        <v-text-field 
          v-model="item.weight"
          :value="item.weight"
          type="number"
          :rules="myRule"
          outlined
          dense
        /> 
      </div>
  </template>
</v-data-table>

Rules

data: () => ({
  myRule: [ 
    v => Number.isInteger(Number(v)),
    v => ( Number(v) && Number(v) >= 1 ) || 'Min: 1',
    v => ( Number(v) && Number(v) <= 99 ) || 'Max: 99',
  ],
}),

I only need to validate the input for the selected row, can anybody help me how to validate between checked box and v-text-field


Solution

  • You can use conditional syntax to put correct set of rules for your number field:

    <v-data-table
      v-model="selected"    
      item-key="name"
      show-select
      :headers="headers"
      :items="desserts"
      :items-per-page="5"
    >
      <template #[`item.calories`]="{ item }">
        <div class="w-100">
          <v-text-field 
            v-model="item.weight"
            :value="item.weight"
            type="number"
            :rules="selected.find(it => it.name === item.name) !== undefined ? myRule : []"
            outlined
            dense
          /> 
        </div>
      </template>
    </v-data-table>
    ...
    data () {
      return {
        myRule: [ ...your rules ],
        selected: [ ...selected values ],
        headers: [ ... ],
        desserts: [ ... ]
      }
    }
    

    CodePen playground is here