简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM