简体   繁体   English

validate.js验证数组元素

[英]validate.js validating array elements

I have a java script object that contains two array properties: 我有一个包含两个数组属性的Java脚本对象:

I'm using the validate.js library. 我正在使用validate.js库。

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. 购买数组包含至少1个购买但最多5个购买,并且数量始终为数字。

How can i do that with validate.js? 我该如何使用validate.js?

You could make a custom validator , let's call it array : 您可以创建一个自定义验证器 ,我们将其称为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 然后在对customer.purchases数组进行迭代时,在渲染块中,您可以通过检查customerErrors.purchases.errors[index].error.qty来查看是否有任何购买商品有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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