`validate.js verifying the elements within an array`

One of the challenges I'm facing in my JavaScript project is dealing with objects that have two array properties included. As part of my development process, I've decided to utilize the resources provided by the validate.js library.

To illustrate, let's take a look at an example:

var customer = {
   name: 'Ted',
   address: 'some address',
   friends: ['Michelle','Elon'],
   purchases: [{ qty:1, goods: 'eggs'}, { qty:2, goods: 'apples'}]
}

Currently, I am seeking to implement validation for the following criteria:

  1. Ensure that the array of friends only consists of string elements.
  2. Validate that the array of purchases includes between 1 and 5 entries while also confirming that the quantity (qty) field is always numeric.

I would appreciate guidance on how to accomplish this using validate.js.

Answer №1

If you want to create a personalized validator, you can develop a custom validation method named array:

import validate from 'validate.js/validate'
import isEmpty from 'lodash-es/isEmpty'

validate.validators.array = (arrayItems, itemConstraints) => {
  const arrayItemErrors = arrayItems.reduce((errors, item, index) => {
    const error = validate(item, itemConstraints)
    if (error) errors[index] = { error: error }
    return errors
  }, {})

  return isEmpty(arrayItemErrors) ? null : { errors: arrayItemErrors }
}

To implement this custom validator, follow these steps:

const customerConstraints = {
  purchases: {
    array: {
      qty: {
        numericality: {
          onlyInteger: true,
          greaterThan: 0,
          lessThanOrEqualTo: 5
        }
      }
    }
  }
}

const customerErrors = validate(customer, customerConstraints)

When looping through the customer.purchases array in your code, you can check for any errors in purchase items using

customerErrors.purchases.errors[index].error.qty

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

Encoding identification data from JSON using ColdFusion

Hello everyone, I've been puzzling over how to intercept and encrypt database record ID from a JSON request in ColdFusion. Below is the code I have so far, along with my unsuccessful attempt. Any assistance would be greatly appreciated. <cfquery ...

Monitoring and recording Ajax requests, and retrying them if they were unsuccessful

As a newcomer to Javascript, I'm diving into the world of userscripts with the goal of tracking all Ajax calls within a specific website. My objective is to automatically repeat any failed requests that do not return a status code of 200. The catch? T ...

Tips for Passing the correct ID to the modal component in reactJs

Looking for some assistance. The issue I'm encountering is that the modal isn't displaying the correct ID of the data I wish to delete Here is my DataTable.jsx code: import React, { useState, useEffect } from "react"; import axios from ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Execute controller action upon item selection within KODataTable MVC table

I am displaying data in a table using AJAX to call an Action that returns a JSON list. Output: I want each user (row in the table) to be clickable and linkable to an edit page (Admin/Edit/Id). This can be done either by clicking on them or by having an E ...

What is the purpose of passing data into the 'success' function of an AJAX request?

Recently, I embarked on a journey to learn jQuery and AJAX, but I found myself tangled in confusion when it came to AJAX requests. To gain practice, I decided to create a simple TodoApp using Node, jQuery, and Bootstrap. While I managed to grasp GET and P ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Running PHP scripts from JavaScript

Currently working on a PHP project that involves a dropdown select button in a webpage. The goal is to call a JavaScript function whenever the value of the dropdown changes, and then pass this selected value to retrieve additional details from a MySQL da ...

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...

Storing JSON data in LocalStorage or within the App on Ionic 2

I am currently in the process of developing a mobile app for both IOS and Android platforms. The app will feature a list of objects including images, names, etc., which are stored on a backend server powered by node.js. My goal is to allow users of the ap ...

Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from. window.onload = function(){ document.getElementById("submit").onclick = displaySelectedStudent; } function displaySelectedStu ...

What could be the reason for the Express function Router() returning a value of undefined?

Currently, I am working with TypeScript and Express to develop an API that adheres to the principles of Clean Architecture. To organize my application, I have structured each route in separate folders and then imported them all into an index.ts file where ...

Data is stored in Django Fullcalendar without saving it in the database, instead a primary key is generated

I am currently facing an issue where the actual data is not being saved in the database. Whenever I click the register button after inputting the data, an empty data entry gets saved and a primary key is created. There are no error messages being displayed ...

Uploading files with Multer and handling the JSON object

Is there a way to send both a file and a JSON object containing data using multer? I came across this thread, but it only explains how to attach one field at a time. Here's what I currently have on the client side: request .post(uploadPOSTUrl) . ...

Encountering a Javascript error while trying to optimize bundling operations

After bundling my JavaScript with the .net setting BundleTable.EnableOptimizations = true;, I've encountered a peculiar issue. Here's the snippet of the generated code causing the error (simplified): var somVar = new b({ searchUrl: "/so ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

The jQuery plugin is not functioning properly on the subdomain

Encountered an issue where a jQuery plugin is not loading in Chromium for a peculiar reason. Interestingly, the plugin loads fine when accessing the page through the root domain but fails to load when accessed via a subdomain in Chromium. However, everyth ...

Updates to $scope are not reflecting in the application

My input includes a datalist that is populated by an angular get request as the page loads. <input list="data" /> <datalist id="data"> <option ng-repeat="item in items" value="{{item.data}}"> </datalist> The $http call is straig ...

How to ensure a div within an anchor tag occupies the full width in HTML and CSS?

In my code, I am working on creating multiple small boxes with images and centered text inside. The goal is to have these boxes clickable, where clicking the image will take you to a specific link. On desktop, I want a hover effect that darkens the image b ...