Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this

varientSections: [
    {
      type: "",
      values: [
        {
          varientId: 0,
          individualValue: ""
        }
      ]
    }
  ]

To ensure uniqueness, I implemented a custom validation function named isDuplicate to check for duplicate values in the "type" property. Here's an example:

varientSections: [
    {
      type: "Basket",
      values: [
        {
          varientId: 0,
          individualValue: ""
        }
      ]
    },
    {
      type: "Basket", // ERROR: Duplicate with the "above" object
      values: [
        {
          varientId: 1,
          individualValue: ""
        }
      ]
    }
  ],

Although my custom validation works correctly, the $invalid property is false for all objects in the array. Consequently, all objects are highlighted in red.

Here is the code snippet for my validation logic:

validations: {
varientSections: {
  $each: {
    type: {
      required,
      isDuplicate(type, varient) {
        console.log(varient);
        const varientIndex = this.varientSections.findIndex(
          v => v.type === type
        );

        var isWrong = true;
        this.varientSections.forEach((varObject, index) => {
          if (index !== varientIndex) {
            if (varObject.type === varient.type) {
              isWrong = false;
            }
          }
        });

        return isWrong;
      }
    },
    values: {
      $each: {
        individualValue: {
          required
        }
      }
    }
  }
}
},

Answer №1

This example demonstrates how it could look.

<div v-for="(vs, index) in varientSections" :key="index">
    <input :class="{'is-wrong': $v.varientSections.$each[index].type.$error}" type="text" v-model="vs.type">
    <input :class="{'is-wrong': $v.varientSections.$each[index].value.$error}" type="text" v-model="vs.value>
</div>

Customize the error styling according to your requirements.

Answer №2

When faced with a similar issue, I discovered that the solution is actually quite straightforward once you understand the concept behind it. Essentially, your validator should only be triggered if the current item is identical to any previous items.

You can implement something like this:

validations: {
  varientSections: {
    $each: {
      isUnique(currItem, itemArr) {
        // Find the index of the first item in the array that has the same type
        var firstIdx = itemArr.findIndex((item /*, index, arr*/) => currItem.type === item.type );
        // If it's the same as the current item then it is not a duplicate
        if(currItem === itemArr[firstIdx])
          return true;
        // All others are considered duplicates
        return false;
      },
      type: { required }
    }
  }
}

Answer №3

it worked well for me!

 <b-row v-for="(field,index) in fields" :key="index">
   <b-colxx lg="6">
     <b-form-group :label="$t('target.name')">
       <b-form-input v-model="field.name" :state="!$v.fields.$each[index].name.$error"/>
       <b-form-invalid-feedback v-if="!$v.fields.$each[index].name.required">name is    required</b-form-invalid-feedback>


     </b-form-group>

   </b-colxx>
   <b-colxx lg="6">
     <b-form-group :label="$t('target.value')">
       <b-form-input v-model="field.value" :state="!$v.fields.$each[index].value.$error"/>
       <b-form-invalid-feedback v-if="!$v.fields.$each[index].value.required">value is    required</b-form-invalid-feedback>
     </b-form-group>
   </b-colxx>
 </b-row> 
 

.

 data() { 
      return {
          fields: [
                    {name: null, value: null},
                    {name: null, value: null} ]  
              } 
           }, 

.

validations: {
          fields: {
           $each: {
             name: {
               required
             },
             value: {
               required
             }
           }
   
   
       },
     },

Answer №4

When working with vue3 composable, it is recommended to utilize the helpers.forEach function:

import { useVuelidate } from "@vuelidate/core";  
import { helpers, required } from "@vuelidate/validators";

const form = reactive({
  users: [
    {
      name: "John"
      value: "Doe"
    }
  ]
})

const rules = {
  users: {
    $each: helpers.forEach({
      name: { required },
      value: { required }
    })
  }
}

const $v = useVuelidate(rules, form)

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

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

How to retrieve an element in jQuery without using the onclick event listener

I'm looking to extract the element id or data attribute of an HTML input element without using the onclick event handler. Here is the code I currently have: <button class="button primary" type="button" onclick="add_poll_answers(30)">Submit</ ...

Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be a ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

Warning: data and salt parameters are necessary, please provide them

Issue: I am encountering an error with registering a new user, specifically when using Postman. I'm not sure why this error is occurring only in Postman. Additionally, I am facing proxy problems where requests cannot be proxied from localhost:3000 to ...

Prevent horizontal HTML scrolling while displaying a layer

I am currently working with a .layer div element that darkens the page to highlight a modal. However, I have encountered an issue where upon triggering the event, the div does not occupy 100% of the screen and the original browser scroll bar disappears. I ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

Experimenting with Vue in conjunction with a web component

I am facing an issue with astrouxds web components in my application. During testing, I am receiving a warning that needs to be resolved. Additionally, I need help on how to properly assert a value in the web component. console.error node_modules/vue/dis ...

Why is the Angular directive '=&' value binding to the scope showing as undefined?

An Angular directive has been defined within my application: (function() { 'use strict'; angular .module('almonds') .directive('security', ['$animate', 'AuthFactory', directive]); fun ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

Enhancing VueJS2 components by optimizing code structure to eliminate duplicate elements

The following code is used in two different components, so please avoid using props. Utilize data variables and largely similar methods but with different component templates. <template> </template> <script> export default { name ...

"Performing a row count retrieval after updating records in a Microsoft SQL Server database

Recently, I have been utilizing the MSSQL NodeJS package (https://npmjs.org/package/mssql#cfg-node-tds) in order to establish a connection with a MS SQL database and execute UPDATE queries. One thing that has caught my attention is that when an UPDATE que ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Tips for showing validation message just one time along with multiple error messages

Exploring ways to implement a dynamic form submit function using jQuery. $('#btnsumbit').click(function() { $('.required_field').each(function() { if ($(this).val() == "") { alert('please fill field'); ret ...

The issue appears to be a missing space before the function parentheses in the

I am just getting started with learning Vue.js. During my project setup, I encountered an issue related to the "Missing space before function parentheses" error message. Below are the details of the 3 errors that I came across: ✘ http://eslint.org/docs ...

Rendering a page for a missing resource

Within the App.js file, the routes component is currently only wrapping a portion of the website. However, I would like the NotFound component to be rendered for the entire page if an incorrect URL is entered. Can you please provide guidance on how this ...

Opt for router-link over web route when working with Laravel

While working with Laravel 9 and Vue 3, I encountered a peculiar issue. When navigating to a link by clicking on the menu, everything worked as expected. However, if I tried to access the same link by directly typing the URL or refreshing the page, I would ...

Magnific Popup is causing a glitch in my Ajax cart slider, preventing my code from functioning properly

Currently, I have implemented an Ajax cart slider that slides from right to left whenever an item is added to the cart. Customers are given the option to add a product with an image to their cart and can view the image directly from the cart by clicking on ...

Can a jQuery object be generated from any random HTML string? For example, is it possible to create a new link variable like this: var $newlink = $('<a>new link</a>')?

I'm looking to create an object without it being attached to the dom. By passing a HTML string, I want to insert the element into the dom and still have a reference to it. ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...