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.

https://i.sstatic.net/OuxCd.png

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

Are foreign characters the culprit behind the JSON parsing problem?

I am encountering an issue while attempting to parse a field containing JSON data returned from an API. The data includes various unusual characters like East Asian symbols and curly quotes, causing this error to appear. I am unsure of how to resolve it - ...

Implement a personalized callback function for a specific resource

Currently, I am using angularjs version 1.1.5 and have a service provider for a resource. In one specific use case, the returned response needs to be reprocessed and some information normalized. Although this is a special case, the resource is utilized thr ...

NodeJS - Issue: The procedure specified could not be located in the bcrypt_lib.node

After upgrading from Node.js 0.12.7 to 4.2.1, I encountered an error when attempting to start my server: $ node server.js C:\Users\me\documents\github\angular-express-auth\node_modules\bcrypt\node_modules\bindi ...

Tips for customizing the appearance of Material UI's time picker diolog styles

I am currently incorporating the Material UI Time Picker from GitHub, specifically TeamWertarbyte's repository. My task involves modifying the color of the time displayed. In the image provided, I aim to customize the color of the time shown as 11:3 ...

Trigger a popup using the javascript .link() method

I am currently using ag-grid to present JSON data. When the values are located within nested objects, I have to utilize a valueGetter from the grid API to map to the appropriate value. The value getter returns a value for each row and the grid matches it t ...

Are multiple .then(..) clauses in Javascript promises better than just using one .then(..) clause?

In this particular scenario, I have set up a basic 'toy' node.js server that responds with the following JSON object: { "message" : "hello there" } This response is triggered by making a GET request to "http://localhost:3060/" So, it's reall ...

The controller and node js request associated are invisible to my HTML page

Here is my HTML code. I have just created a unique controller for a specific part of the code. <div class="mdl-grid" ng-controller="ValueController"> <div class="mdl-card mdl-shadow--4dp mdl-cell--12-col"> <div class ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

What steps should I take to make the code in jsfiddle functional on my Visual Studio Code platform?

const canvasEle = document.getElementById('drawing-container'); const canvasPad = document.getElementById('pad'); const toolbar = document.getElementById('toolbar'); const context = canvasEle.getContext('2d'); const ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Access SCSS variable values in Angular HTML or TypeScript files

So, I've been looking into whether it's feasible to utilize the SCSS variable value within HTML or TS in Angular. For instance: Let's say I have a variable called $mdBreakpoint: 992px; stored inside the _variable.scss file. In my HTML cod ...

Ways to leverage the power of Reactivity APIs in Vue.js

In my Vue application, I am trying to create a Drop Down Menu by using a variable called "showDropDown". The idea is to use a v-if directive to check if the value of showDropDown is true, and then display the menu accordingly. Additionally, I want to imp ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

Update a particular package using Node

Is there a way to update Browser-sync without updating all my node packages? I need the version with the Browser-sync GUI, but I don't want to update everything else. ├─┬ <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Retrieving selections from a group of checkboxes and managing their addition or removal in an array

Currently, I am in the process of creating a form that includes a group of checkboxes. My goal is to be able to capture the value of a specific checkbox when it is clicked and add it to an Array using the useState hook. If the checkbox is unchecked, I wan ...

Issue encountered in Vite Preview: Uncaught (in promise) SyntaxError: JSON.parse found an unexpected character at the beginning of the JSON data, line 1 column 1

Encountering the error message Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data when running vite preview after running vite build. Here is my vite.config.js: import { defineConfig } from "vite&q ...

Information submitted through an ajax request does not get saved in the $_POST array

After successfully executing an AJAX request using GET, I decided to try POST this time. However, when attempting to send data, a baffling error message appeared in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does ...

Encountering difficulties reaching $refs within component method

Trying to access a ref defined within a template when an element is clicked. Here's the HTML: <!DOCTYPE html> <html lang="en"> <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protectio ...

Exploring the contrast between an amd.js file and a main.js file within the dist directory of a JavaScript node project

Looking into a JavaScript project utilizing Node and Webpack, I've noticed that within the node_module directory there is a lib folder containing an xyz.js file. Additionally, in the dist folder of the node_module, there are xyz.amd.js, xyz.main.js, a ...