5

I am trying to validate a dynamically added input field. Whenever I just have one row of inputs to validate, it works great.

Working case example: enter image description here

However, whenever I add a row, the validation validates both the first row, and the added row - instead of validating each row individually. This is the problem case.

Problem case example:

enter image description here

The docs suggest giving a unique id for the :key, however, even after adding a unique id field, I'm seeing the issue.

Here is my code for generating the inputs

   <!-- Generate input fields and v-model -->
    <tr v-for="(row, rowIndex) in dataFields" :key="row.id">
      <td v-for="(fieldName, fieldNameIndex) in fieldNames" :key="fieldNameIndex">
        <!-- create first row and add valdiation -->
        <input
          type="text"
          class="input-style"
          v-model="dataFields[rowIndex][fieldName]"
          v-validate.initial="'required'"
          :name="fieldName"
        >
        <br>
        <span> errors.first(fieldName)}}</span>

And here is a full demo of the problem: https://codesandbox.io/s/vue-template-rtjj9?fontsize=14

How can I add validation to each dynamically added row?

1 Answer 1

4

You can add rowIndex to name to make them different

<tr v-for="(row, rowIndex) in dataFields" :key="row.id">
  <td v-for="(fieldName, fieldNameIndex) in fieldNames" :key="fieldNameIndex">
    <!-- create first row and add valdiation -->
    <input
      type="text"
      class="input-style"
      v-model="dataFields[rowIndex][fieldName]"
      v-validate.initial="'required'"
      :name="fieldName + rowIndex"
      :data-vv-as="fieldName"
    >
    <br>
    <span @click="clicky()">{{errors.first(fieldName + rowIndex)}}</span>
  </td>
</tr>

Note that you can use data-vv-as to customize the name field in validation message.

Demo here

Sign up to request clarification or add additional context in comments.

Comments

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.