Guide on enforcing form validation with the utilization of a for loop in conjunction with an error array

When I click a button, I want to validate input fields for emptiness. Specifically, I am filtering an array to check if any of the inputs are empty. My goal is to add an error message to the array only for those inputs that are empty. However, the issue I'm facing is that the error message is being added even for inputs that are not empty.

<template>
    <form>
      <div v-for="(learning, i) in general.learnings" :key="i">
        <input
          type="text"
          v-model="general.learnings[i]"
          maxlength="120"
        />
      </div>
      <p
        style="background: red"
        v-for="(i, index) in errorList"
        :key="'A' + index"
      >
        {{ i }}
      </p>
      <button @click="save">Save</button>
    </form>
</template>

<script>
export default {
  methods: {
    save(e) {
      
      this.general.learnings.filter((e, index) => {
        if (!e[index]) {
          this.errorList.push("Error")

        } else if (e[index] !== "") {
          this.errorList = [""];
        }
      });
      e.preventDefault();
    },
  },
  data() {
    return {
      errorList: [],
      general: {
        learnings: ["", ""],
      },
    };
  },
};
</script>

It seems like the issue may be with

this.errorList.push("Error")
. For further reference and testing, you can view the code on CodeSandbox. If you input some text, press the button, delete the content, and press the button again, you'll notice that the functionality is not ideal. Any help or guidance on resolving this would be greatly appreciated.

Answer №1

After incorporating @flaxon's code, I have implemented a solution where errors are displayed only for specific indices within my application. To achieve this, I made slight modifications to the validation check inside the save method.

<div v-for="(learning, i) in general.learnings" :key="i">
      <input type="text" v-model="general.learnings[i]" maxlength="120" />

      <p style="background: red" :key="'A' + index">
        {{ errorList[i] }}
      </p>
    </div>

save(e) {
  this.errorList = [];
  this.general.learnings.filter((e, index) => {
    if (e === "") {
      this.errorList.push("Error");
    } else {
      return true;
    }
  });
  e.preventDefault();
},

Answer №2

Visit the CodeSandbox project here

I made adjustments to the structure by placing the paragraph inside the div element, and now it only shows the error specific to that index.

<div v-for="(learning, i) in general.learnings" :key="i">
      <input type="text" v-model="general.learnings[i]" maxlength="120" />

      <p style="background: red" :key="'A' + index">
        {{ errorList[i] }}
      </p>
    </div>

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

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Conceal the element if the output of express is void

I am currently developing an app using nodejs and express. I am retrieving JSON data from an endpoint and displaying it on the page based on the values received. The issue I am facing is that if I receive a null or undefined value from the JSON data, how ...

Getting just the page path in Express.js can be achieved by utilizing the `req.path

Is there a way to extract only the page path in express.js? I need to dynamically render pages based on the URL. For example, when accessing http://example.com/a_lion, my code should search for an object in an array with a title that matches the path (a_li ...

How can we prevent components from rendering in React when their state or props have not changed?

I encountered a problem in my project where I have a main component that serves as the parent component of my project. Inside this main component, I have defined routes for other components and directly imported some components like a Side Navbar and Login ...

What causes parseInt to transform a value into infinity?

Here is what I'm working on: let s = '50'; let a = parseInt(s); console.log(a); //outputs 50 console.log(_.isFinite(a)); //outputs false I'm curious why parseInt turns 'a' into infinity when 'a' is set to 50? ...

"Python - Exploring the World of Array Slicing

I have been given an assignment by my university to analyze a specific slicing operation. A = array([[1,2,3],[4,5,6],[7,8,9]]) A[0,arrange(3)<>0] A[1,arrange(3)<>1] A[2,arrange(3)<>2] The operation in question is A[k, arange(n)<>k ...

What is the best way to display a <div> depending on the screen size in React JS using a global variable, without utilizing state management?

I am attempting to display a message based on the screen resolution in ReactJS. I am utilizing a function component and trying to accomplish this without using state, by using a global variable. const isDesktop = window.innerWidth; {isDesktop > 768 ? ...

What is the best way to incorporate a JavaScript file into a webpage specifically for browsers that are using IE 7 or an earlier version?

Is there a way to dynamically include a Java Script file depending on a certain condition? For instance, I am looking for a solution to incorporate a JavaScript file that provides JSON support specifically when the user's browser is Internet Explorer ...

clear form input upon click event in AngularJS

Description: I am incorporating ui-router to load form pages upon clicking an icon. Every time the user clicks on the icon, a new form should load with all fields reset. By adding ng-click to the icon, we can easily reset the form values. index.html &l ...

Creating dynamic flags with specific parameters using Pentaho and JavaScript

I am looking to optimize my code by finding a better way to achieve this. I have a variable called "hour" and I need to create flags for each hour of the day like so: if (hour == 0) {flag12AM = 'yes'} else {flag12AM == 'no'} if (hour ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

I have developed a function that adds up price values, but for some reason it is always lagging one step behind

I am facing an issue with my React container that has add and subtract functions. These functions are triggered whenever a user clicks on '+' or '-' spans, to calculate the total 'price' of three different 'products' ...

Exploring sections of a non-contiguous array in Numpy by considering them as a single contiguous unit with a

My goal was to create an array of trigrams (three-letter combinations) from a very long character array: # loading data from a source file a = np.random.randint(0, 256, 2**28, 'B').view('c') Instead of inefficiently making a copy, whic ...

Performing an XMLHttpRequest to Submit an HTML Form

Our Current HTML Form Setup This is an example of the HTML form we are currently using. <form id="demo-form" action="post-handler.php" method="POST"> <input type="text" name="name" value=" ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

AngularJS data retrieval timeout function

After reading this response, I am currently in the process of developing a service that can provide data even if the request fails due to timing out. this.getStatus = function() { var timeoutPromise = $timeout(function () { cancele ...

New to Angular: Getting Started with NgModel Binding

Novice query: I am facing an issue with a simple input type=text element linked to ng-model="xyz.zyx", where xyz refers to an object. In my controller, I initialize this object and set the value for the property zyx as shown below: xyz { zyx: $scope.zz ...

Using the parent id in knockoutJs to create a nested menu

I'm currently attempting to create a nested menu using the JSON data provided by the client. Here is the data: var serverData = [ { Id: "menuColorSearch", Text: "Color search" }, { Id: "menuAncillaryProductM ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...