14

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?

1

1 Answer 1

17

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Good day, I am new to mongoose, I've been too many articles and forums regarding element(string) validation inside array but nothing works for me. I guess you may help me. As of now I have tags: [ {type: String, minLength: 2, maxLength:50, trim: true}] which is only min, maxLength is not working. Thank you
I think the custom validator should check whether the input is an array or not. It should also check array elements are of type 'object' or not. In case of Objects it should use 'validate', and in case of primitive types it should use 'validate.single'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.