VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance:

data(){
   return{
inputs: [
      {
        id: 1,
        label: "first name",
        type: "text",
        placeholder: "",
        model: "",
        rules: "required"
      },
      {
        id: 2,
        label: "last name",
        type: "text",
        placeholder: "",
        model: "",
        rules: "required"
      } ]
   }
}

For the HTML implementation:

  <ValidationObserver v-slot="{ handleSubmit }">
    <b-form @submit.prevent="handleSubmit(onSubmit)" class="p-5">
      <div v-for="inp in inputs" v-bind:item="inp" :key="inp.id">
        <ValidationProvider name="Value" :rules="inp.rules" v-slot="validationContext">
          <b-form-group
            :id="'input-group-'+inp.id"
            :label="inp.label"
            :label-for="'input-'+inp.id"
            label-cols="4"
            label-cols-lg="2"
          >
            <div v-if="inp.type != 'select'">
              <b-form-input
                :type="inp.type"
                :placeholder="inp.placeholder"
                v-model="inp.model"
                :id="'input-'+inp.id"
                :name="'input-'+inp.id"
                :state="getValidationState(validationContext)"
                aria-describedby="input-1-live-feedback"
              ></b-form-input>
              <b-form-invalid-feedback
                :id="'input-'+inp.id+'-live-feedback'"
              >{{ validationContext.errors[0] }}</b-form-invalid-feedback>
            </div>
          </b-form-group>
        </ValidationProvider>
      </div>

      <button type="submit">Submit</button>
    </b-form>
    <div>
      Look at the output
      {{show}}
    </div>
  </ValidationObserver>

While this method works well for dynamically generating inputs in the HTML, I encounter an issue when trying to add form validation to these dynamic forms. Desired Outcome: If the form has a submit button, with inputs that have 'required' validation, the expectation is that upon clicking the button without inputting anything, all inputs should display a warning stating "this input is required" or a similar message.

The Issue: When the submit button is pressed without entering anything in the inputs, only the last input displays the warning message.

For reference, here is the link to the codesandbox example showcasing this issue: https://codesandbox.io/s/codesandbox-733yf?fontsize=14&hidenavigation=1&theme=dark&file=/src/Demo.vue

Answer №1

It is highly recommended (and seems to be mandatory) to assign a vid to your ValidationProvider components when working within a v-for loop, as shown below:

    <ValidationProvider :vid="'vp'+inp.id" name="Value" :rules="inp.rules" v-slot="validationContext">

By following this practice, all error messages became visible in the example provided.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The image selection triggers the appearance of an icon

In my current project, I am working on implementing an icon that appears when selecting an image. The icon is currently positioned next to the beige image, but I am facing difficulties in making it disappear when no image is selected. Below are some image ...

NodeJS unexpectedly exhibiting peculiar array functions

Within my NodeJS code, I have the following implementation: /* server.js */ 'use strict'; const http = require('http'), url = require('url'); METHODS = ['GET','POST','PUT','DELETE&a ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Tips for successfully using JSON data in AJAX requests to PHP servers

I am currently working on a project involving a shopping cart. My task is to pass an array of objects that have been added to the shopping cart and stored in localStorage over to a PHP page for database insertion. console.log(localStorage.getItem("shoppin ...

Hide modal once form has been successfully submitted

Is it best practice to pass handleClose into ForgotPasswordFormComponent in order to close the modal after form submission, or is there a better way to achieve this? <StyledModal open={openModal} onClose={handleClose} closeAfterTransition slots={{ bac ...

Is there a way to automatically generate and allocate an identifier to an input field?

I've written the code below, but I'm having trouble figuring out if it's accurate. Specifically, I can't seem to access the text inputs that have been created by their respective id attributes. for (i=0;i<t;i++) { div.innerHTML=div. ...

Servlet question: What causes the XMLHttpRequest responseText to consistently appear empty?

I've been going crazy trying to figure out how to solve this issue. I have a servlet deployed in Tomcat running on localhost:8080 that looks like this: @WebServlet(urlPatterns = { "/createcon" }, asyncSupported = true) public class CreateCon extends ...

The server at localhost responds with a CANNOT GET/ error message

This is the code snippet I've been working on: const express = require('express'); const app = express(); const bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: false})); app.use(bodyparser.json()); c ...

Difficulty encountered when attempting to implement custom filtering based on condition in HTML using Angular

I'm still new to angular, so please bear with me if this question seems trivial. I have a collection of integers in my controller and I need to filter it to only show items that meet a certain condition. Initially, I attempted the following: <div ...

I'm facing an issue where the data I retrieved is not displaying properly in my template within nuxt 3

After fetching data from an api, I can see it logged in my async function. However, the data stored in my array is not rendering on my template in Nuxt 3 The script setup includes: //ARRAY OF ALL THE DAILY WEATHER DATA PER DAY let allDataWeather=[]; ( ...

Is there a straightforward way to upload a folder in a ReactJS application?

I am searching for a way to upload a folder in ReactJS. I have a folder with .doc and .docx files in it, and I want the user to be able to upload the entire folder when they click the browse button. I need to prevent the user from selecting individual fi ...

Verify the operation within a pop-up box using ruby watir

Is it possible to confirm a modal dialog window in Internet Explorer using Ruby Watir? Here is the JavaScript code for the modal dialog: jQuery('#yt100').on('click', function(){return confirm('modal dialog window text');}); ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

How can I execute a different seed file using Sequelize-cli before running the main seed file?

I recently created a seeder file using sequelize-cli to bulk insert data into a MySQL database, and everything is working perfectly. However, one of the fields I am inserting (userId) requires a value that is already present in another table called User. ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Generate projectiles within a game periodically

I've created a game that features a main character and enemy soldiers who shoot back. I'm facing an issue where only one enemy soldier shoots at intervals, even though I initially used setInterval for both of them. Any suggestions on how to fix t ...

Is there a way to prevent users from selecting certain days in ion-datetime?

After searching through the official documentation, I couldn't find a solution. I am in need of a function similar to the jQuery datepicker beforeshowday function. My goal is to disable all weekends (Saturday and Sunday) in upcoming dates so that user ...

Differences Between Data Captured from Form Submissions and Data Obtained Through Ajax

When attempting to incorporate reCAPTCHA into my MVC site, I encountered an issue where it would not validate unless submitted from a form. Here is the current implementation: @using(Html.BeginForm("VerifyCaptcha", "Signup") ) { @ReCaptch ...

Dealing with undefined props in a React component can be tricky. If you're running into issues with props being undefined

I'm encountering an issue where the props from getServerSideProps are showing as undefined when I attempt to pass them into a React component. Even though my code seems correct and everything works fine on the backend, I can't seem to determine ...

Using spline3D in combination with Vue or Nuxt: A beginner's guide

I recently started experimenting with Vue and wanted to create an interactive site using spline 3D. While there is a library for reactjs in splinetool, I couldn't find one for Vue. I attempted to import @splinetool/runtime and export it, but the 3D sc ...