Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate.js validating array elements

I have a java script object that contains two array properties:

I'm using the validate.js library.

For example:

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

I want to validate the following:

  1. That the array of friends contains only elements of type string.
  2. That the array of purchases contains at least 1 purchase but max 5 purchases and that the qty is always numeric.

How can i do that with validate.js?

like image 578
Tal Avissar Avatar asked May 04 '16 18:05

Tal Avissar


People also ask

How do you validate an array in JavaScript?

In JavaScript, we can check if a variable is an array by using 3 methods, using the isArray method, using the instanceof operator and using checking the constructor type if it matches an Array object. The Array. isArray() method checks whether the passed variable is an Array object.

How do you check if all values in array are true JavaScript?

To check if all of the values in an array are equal to true , use the every() method to iterate over the array and compare each value to true , e.g. arr. every(value => value === true) . The every method will return true if the condition is met for all array elements. Copied!

How do you check if a value is in a list JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.


1 Answers

You could make a custom validator, let's call it 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 }
}

and then use it like:

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

const customerErrors = validate(customer, customerConstraints)

then in the render block when iterating over the customer.purchases array you can see if any purchase items have an error by checking customerErrors.purchases.errors[index].error.qty

like image 125
Cumulo Nimbus Avatar answered Nov 15 '22 07:11

Cumulo Nimbus