Home > database >  How to validate multiple fields with same name in vue.js
How to validate multiple fields with same name in vue.js

Time:10-19

I have some input fields with same name, but when one of this input is invalid,all the other input fields display error.What is a good way to resolve this.

    <tr v-for="(form, index) in forms"
        :key="index">
          <div>
            <input
              
              @keyup.prevent="validateField('sourceName')"
              type="text"
              v-model="form.description"
            >
          </div>
          <span v-if="hasErrorName">
            {{ msgName }}
          </span>
       </tr>

methods: {     
    validateField(field) {
      if (field === 'name') {
        if (!this.form[0].description) {
         this.hasErrorName = true;
         this.msgName = 'Source Name is required.';    
       } else {
         this.hasErrorName = false;
         this.msgName = null;
      }
    }
  }

CodePudding user response:

You seem to be using a single variable msgName to track all the entries. i'll modify your code a bit and you can try to change it. You can define msgName as an empty object msgName: {} in your data object.

<tr v-for="(form, index) in forms"
        :key="index">
          <div>
            <input
              
              @keyup.prevent="validateField('sourceName', index)"
              type="text"
              v-model="form.description"
            >
          </div>
          <span v-if="msgName[index]">
            {{ msgName[index] }}
          </span>
       </tr>

methods: {     
    validateField(field, index) {
      if (field === 'sourceName') {
        if (!this.form[index].description) {
         this.msgName[index] = 'Source Name is required.';    
       } else {
         this.msgName[index] = null;
      }
    }
  }
  • Related