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?
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.
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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With