Validating deeply nested arrays of strings using Vuelidate

Within my Vue file, I am working with data that has the following structure:

data() {
  return {
    formData: {
      name: 'foo',
      objects: [
        {id: 0, name: 'a', props: []},
        {id: 1, name: 'b', props: ['2', '23']},
        {id: 2, name: 'c', props: ['44']},
        {id: 3, name: 'd', props: []}
      ]
    },
    currentObj = null,
    currentPropIndex = null
  }
}

The number of objects in the array objects is variable, as is the contents of the props array where string values can be added or removed. I am trying to use Vuelidate to validate each and every value in the props array for each object whenever it changes. This is what I have attempted:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      props: {
        $each: {
          required, numeric, maxLength: maxLength(5)
        }
      }
    }
  }
},

Computed property:

propsErrors() {
    const errors = [];
    if ( this.currentObj) {
      // const objIndex = _.findIndex(this.formData.objects, o => o.id === this.currentObj.id)
      if (!this.$v.formData.objects['props'][this.currentPropIndex].$dirty) {
        return errors;
      }
      !this.$v.formData.objects['props'][this.currentPropIndex].maxLength && errors.push('Max 5 digits')
      !this.$v.formData.objects['props'][this.currentPropIndex].required && errors.push('Required')
      !this.$v.formData.objects['props'][this.currentPropIndex].numeric && errors.push('Digits only')
    }
    return errors
  },

Here is the code for a Vuetify text field:

<v-text-field single-line flat dense required
  v-model="object.props[index]"
  :error-messages="propsErrors"
  label="Prop"
  height="30"
  @click="setCurrents(protocol, index)"
  @blur="$v.formData.protocolPorts['manual_ports'][index].$touch()"
  @input="$v.formData.protocolPorts['manual_ports'][index].$touch()" />

The setCurrents function simply sets the currently edited object and prop index:

setCurrents (protocol, index) {
    this.currentObj = protocol;
    this.currentPropIndex = index;
  }

When testing the page and clicking on the text field, I come across this error:

Error in render: "TypeError: Cannot read property 'props' of undefined"

I made an adjustment to the propsErrors method (objIndex is currently commented out in the above code)

this.$v.formData.objects[objIndex]['props'][index].maxLength && errors.push('Max 5 digits')

Updated input field (oi refers to object index):

@input="$v.formData.objects[oi].props[index].$touch()"

Further validations are defined as:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      required,
      $each: {
        props: {
          $each: {
            required, numeric, maxLength: maxLength(5)
          }
        }
      }
    }
  }
},

Despite these modifications, the errors persist. Any suggestions are greatly appreciated.

Answer №1

Although I haven't had experience with Vuelidate, I stumbled upon this example that I found quite helpful and closely aligned with your current project goals here

To make a small adjustment in the Vue instance data, you should modify it from

currentObj = null,
currentPropIndex = null

to

currentObj: null,
currentPropIndex: null

Answer №2

The $each feature has been eliminated, for more information check out this link

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

Using JavaScript to ensure that at least one radio button has been selected

Seeking help with fixing my JavaScript form validation for a newbie like me. I suspect the issue lies within my selector (marked as Not Working Comment) but lack the expertise to resolve it. Trying to implement validation for various input types in my form ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Method for extracting URL parameters while utilizing a hash within the URL

I've been exploring AJAX with hash in URL using prototypejs. Consider the following URL: http://example.com/#/example/104?v=0&d=a&rpp=10 print_r( $_GET ); // output: array() However, when I try this URL: http://example.com/example/104?v= ...

Retrieving JSON information stored in a JavaScript variable

I'm feeling a bit embarrassed to admit it, but I am still learning the ropes when it comes to Javascript development. I've hit a roadblock and could really use some help from the experts here. Thank you in advance for all the assistance this comm ...

Watch an object with AngularJS's $scope and detect and respond only to changes in its property values

Currently, I am monitoring scope changes using a simple watch like this: $scope.$watch('myObject', function(newValue, oldValue) { if (newValue !== oldValue) { return newValue; } }, true); In this case, myObject is an ordinary ob ...

Hover over parts of an image to bring attention to them

I am interested in developing a webpage featuring a black and white image of 5 individuals. When hovering over each person, I would like them to illuminate and display relevant information in a dialog box next to them. Do you have any tips on how I can ac ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

The problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

JavaScript - Relocating the DIV Scrollbar to the Top Upon iFrame SRC Modification

re: I have created a user-friendly website for comparing different potential "expat" cities. Each city has links (target=iframe) for cost of living data, Wikipedia, expat blogs, climate information, and Google Maps. In the left column, there are control ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

Allowing SVGs to be clickable without disrupting the functionality of YouTube videos

I'm experiencing an issue with the overlapping of the svg and YouTube elements. If you hover your mouse over, just to the right of the svg and click, instead of opening the video, it redirects you back to the previous page. Clicking on the area betw ...

Exploring the Dynamic Resizing of Geometry Meshes in three.js

Is there a way to adjust the height of my geometry meshes dynamically? You can check out my demo here. ...

Upgrading object based on dynamic data shifts in Vue using Vuex

My current task involves updating data in a component based on the selection made from a tabs list at the top of the page. The data is sourced from a Vuex data store, and after conducting tests on the data store, everything appears to be functioning correc ...

I'm having trouble getting Parsley JS validation to function properly within a Tiny MCE rich text area. How can I ensure that Parsley.js is aware of any changes made to the content in Tiny MCE?

Utilizing both TinyMCE (version 4.9.10) and Parsley JS (version 2.9.1) on a form presents the challenge of validating TinyMCE fields before form submission. Since TinyMCE generates instances based on HTML textarea fields, applying Parsley attributes like d ...

Guide to transmitting data from a C# WinForm to a completely separate JavaScript client chat application

I am facing a challenge with my chat application where I have a client-side written in JavaScript and a server-side built using WinForms. My goal is to transfer a value from my FrmConsole.cs file to my converse.js file. Is there a method I can use to accom ...

Having trouble accessing the 'checked' property of the checkbox

I've been developing a web application using Vite, JavaScript, jQuery, and Bootstrap. I'm facing an issue where the jQuery .is(':checked') function is not working as expected on one specific page. Despite the checkboxes being checked, t ...

Error encountered with AJAX call when attempting to utilize string method

I am looking to add HTML content to a TinyMCE editor in an ASP.NET MVC project. After some thought, I have found a solution that involves converting the HTML file to a string on the server side and then calling it using Ajax on the client side. Here is a ...

Having trouble sending a JavaScript variable to PHP using Ajax

I have a challenge where I need to pass values of a JavaScript variable to a PHP page and use those values there. However, when I do this, it returns a new HTML page that displays an error message saying "some error". Unfortunately, I cannot figure out why ...

Adjust the background color of the dropdown when toggled

I want to add a background color to my dropdown menu when it's activated. In the demo, the dropdown content overlaps with the text behind it. Currently, I have a scrollspy feature that applies a background color to the nav bar and dropdown menu when s ...

Utilizing JQuery to update the selected item in a menu

Hey there! I'm currently using the jquery chosen plugin and I'm trying to make it so that I can select a menu value based on the selection from another select menu. Unfortunately, my code only works with a simple select menu and I need it to work ...