`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

"Need to refresh localStorage in VueJS after navigating back with this.$router.go(-1)? Here's how

Below is my Login.vue code: mounted() { if (localStorage.login) this.$router.go(-1); }, methods: { axios.post(ApiUrl + "/login") { ... } then(response => { ... localStorage.login = true; this.$router.go(0); ...

Transforming an array of JavaScript objects into arrays of key-value pairs based on a specific property with ES6 syntax

Consider an array of objects like this: myArray = [ {name: 'First', parent: 1, delta: 2}, {name: 'Second', parent: 1, delta: 1}, {name: 'Third', parent: 2, delta: 1} ]; The goal is to transform this array into an objec ...

Identifying when a user is idle on the browser

My current project involves developing an internal business application that requires tracking the time spent by users on a specific task. While users may access additional pages or documents for information while filling out a form, accurately monitoring ...

Develop a JavaScript application that contains a collection of strings, and efficiently sorts them with a time complexity of O(nlog n)

Seeking assistance in developing a JavaScript program that contains an array of strings and must sort them efficiently in O(nlog n) time. Grateful for any guidance... ...

Ajax: client dilemma created by the interaction of two functions

My university homework assignment requires me to develop a small e-commerce website. After logging in, the user will be directed to the homepage where they will receive a JSON object from the server containing product information to dynamically generate th ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

Exploring the functionalities of the componentDidUpdate() method in React JS

In my project, I am trying to dynamically change an API parameter using a click function and render new data accordingly. The issue I encountered is that when I trigger the componentDidUpdate method with an onclick event listener, the first click works fin ...

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP. On the product details page, users can add products to their cart, so I show the total cart value. I need the total amount displayed in a decimal number format (10,2). Currently, when a u ...

Leveraging Ajax for Executing a MySQL Query in PHP upon Clicking the Facebook Like Button

Is it possible to execute a MySQL query whenever a Facebook Like button is clicked on a webpage? I am aware that FB.Event.subscribe('edge.create', function(response) {} is used for such actions. However, my lack of knowledge in Javascript and AJA ...

Difficulty in adding a simple return to render an array in React for list creation

After establishing a basic object, I noticed that it contained an internal object named "orders" with an array of toppings like "Cheese" and "Bacon". To further explore this structure, I segregated the array and directed it to a function called renderToppi ...

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

Is there a way to generate bootstrap divs by parsing csv text?

As I am working on a Bootstrap 3 image gallery, I have noticed that there are multiple recurring divs with a similar structure as shown below: <figure class="col-1 picture-item" data-groups='["groupA"]' data-date-created="2018" data-title=" ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

PHP: Verifying the authenticity of names in multiple languages

As I work on developing a global website using PHP, my goal is to allow users to enter their first and last names in their respective languages and not be limited to English. This means Indian people should be able to type their names in Indian script, Rus ...

What is the most efficient way to align a localStorage variable with its corresponding page?

In my current project, I have developed a component that is utilized in an online science lab setting. To ensure continuity for researchers who navigate away from the page and return later, I have integrated the use of localStorage. The goal is to preserv ...