Validate Wildcard Array of Objects with Express-Validator version 5.2.0 - A Comparison Guide

Struggling to validate an array of objects using express-validator.

Utilizing the "wildcard" and "custom", I'm looping through the objects in the array to compare keys.

The issue arises with an object structured like this:

flavors:[
 { name: '', percentage: '0', ratio: '0' },
 { name: 'Strawberry', percentage: '2', ratio: '0' },
 { name: '', percentage: '3', ratio: '0' }
]

I need to check if "name" is present only when "percentage" > 0.

req.checkBody("flavors","Your recipe has no flavor!").notEmpty();
req.checkBody("flavors.*","Please enter a name for this flavor.").custom(function (value) {
    return (!(value.percentage > 0) && !value.name);
});

This setup functions, but the error output format can be challenging:

{ 'flavors[2]': { 
     location: 'body',
     param: 'flavors[2]',
     msg: 'Please enter a name for this flavor.',
     value: { name: '', percentage: '3', ratio: '0' }
}}

Displaying this in my EJS template becomes complex. How can I modify the output to include an additional key?

{ 'flavors[2].name': { 
     location: 'body',
     param: 'flavors[2].name',
     msg: 'Please enter a name for this flavor.',
     value: { name: '', percentage: '3', ratio: '0' }
}}

Appreciate any assistance on resolving this, thank you! :-)

Answer №1

Currently, native support is not available for this feature. However, there may be some limited functionality when the proposed changes in this GitHub issue are implemented.

In the meantime, you can use lodash's _.toPath() to achieve similar results:

req.checkBody('flavors.*.name').custom((name, { req, location, path }) => {
  const index = _.toPath(path)[1];
  const { percentage } = req[location].flavors[index];

  // If percentage is 0, it will always be considered valid.
  return percentage > 0 ? name !== '' : true;
});

Answer №2

This method can also be utilized temporarily

req
.checkBody("flavors","Please make sure to input a name for this flavor.")
.custom(data => 
   Array.isArray(data) 
      && 
   data.length 
      && 
   data.every(item => item.name && item.percentage > 0));

I trust this can offer some assistance :)

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

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

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 ...

having trouble parsing JSON data

Recently, I decided to experiment with JSON and utilized json_encode to generate a JSON object structured as shown below: [{ "timestamp": "12\/16\/2013 0:00", "curr_property": "7211", "curr_property_cost": "123", "day_pro ...

Building a feedback mechanism with HTML, JavaScript, and MongoDB

I had an idea to develop an employee feedback system that could gather feedback and store it in my MongoDB database. I have included the backend and frontend code below, but unfortunately, I ran into an error: Failed to submit feedback. Please try again ...

Using Vue's v-for directive: Populate HTML dynamically with an event handler (@change) from an array within a component template

This is the setup I am currently using: HTML <question v-for="question in questions" v-bind:id="question.id" v-bind:title="question.title" v-bind:statement="question.statement" v-bind:interaction="question.interaction" @onchange-vg=" ...

Leveraging ForEach to merge two arrays and generate a fresh entity

I am in search of my final result which should be as follows: result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ] Currently, I have two arrays to work with. The first a ...

Tips on incorporating JavaScript files into Angular applications

Struggling to incorporate a JavaScript function into Angular, I have installed the plugin "npm I global payments-3ds". I copied the JavaScript files from node_modules and attempted to call them in my component. Below is an example: import { ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Curious about how to add a date in JavaScript?

Looking for some assistance with the code snippet below: <script language="javascript" type="text/javascript"> function getdate() { var tt = document.getElementById('txtDate').value; var ct = document.getElementById('package& ...

Enhance LCP Performance in Next.js for Faster Loading Speeds

I'm currently working on a next.js project (version 11.1.2) and my goal is to improve the page speed performance. To track this, I am using Google PageSpeed Insight for evaluation. Presently, the scores stand at: 40-50 for mobile (!!) 80-90 for deskt ...

The functionality of extending Jade is currently not functioning correctly

I seem to be encountering an issue with the extends feature in my jade template. I am currently working on a simple todo list web application and have two jade files, layout.jade and login.jade. //layout.jade doctype html html head meta(charset=&apo ...

Compatibility problem arising from the versions of ember-precompile, ember.js, and handlebars.js

Having trouble reading the precompiled templates in my HTML due to compatibility issues between ember-precompile, ember.js, and handlebars.js. My code looks like this: Includes the following files. <script src="../js/libs/jquery-1.10.2.js"></sc ...

Getting an Array Column from a PostgreSQL Stored Procedure

I have a function that generates a query based on this specific answer It is functioning properly, except for when the columns are of type array, which is the result of using array_agg with tuples To Simplify: In real scenarios, the arrays are often pro ...

Retrieve the overall number of Formik errors for a specific field array

In the given Yup validation setup below, there is a nested Formik FieldArray: parentLevel: Yup.array().of( Yup.object({ childrenLevel: Yup.array().of( Yup.object({ childName: Yup.string().required('Name is required') ...

Removing borders from textField in ReactJS can be achieved using a combination of CSS

Is there a way to remove the border from a TextField component? <Box display="flex" alignItems="center" border="1px solid #ccc" borderRadius="4px" paddingLeft="10px"> <Typography variant=&quo ...

Loading website with continuous HTML5 video playback

I'm currently working on a website that features a large section with a video background set to loop. To enhance the user experience, we decided to include a preloading image while the site loads its resources. Our current setup involves using jQuery ...

Utilize the Material UI feature to call the function

How can I pass a function as a prop to my Material UI component if the function is undefined within the component? import React, { Component } from 'react'; import styled from 'styled-components'; import InputBase from '@material- ...

Effective approach for managing a series of lengthy API requests

I am developing a user interface for uploading a list of users including their email and name into my database. After the upload process is complete, each user will also receive an email notification. The backend API responsible for this task is created u ...

The Axios post request is mistakenly sending my data as the key with an empty value instead of sending the entire data object itself

I began by developing the frontend, but now I am looking to create the backend in order to establish a connection with a database. const express = require("express"); const bodyParser = require("body-parser"); const cors = require(" ...

Error: Unable to locate the Vue editor JS module

Currently, I am integrating VUE JS into Laravel and would like to incorporate a block editor using this package. I have included the import statement as follows: import Editor from 'vue-editor-js'. However, upon running the command npm run dev, i ...