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:
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.