Validating Array of Different Object Shapes in Yup

Yup validate array of objects contains at most one object where property = value

After poking through Yup's issues in GitHub, staring at the API docs (the doc for addMethod is really terrible), and testing in Code Sandbox, I found that this works:

Yup.addMethod(Yup.array, 'atMostOne', function(args) {
const { message, predicate } = args
return this.test('atMostOne', message, function(list) {
// If there are 2+ elements after filtering, we know atMostOne must be false.
return list.filter(predicate).length < 2
})
})

The predicate, obviously, is a function that takes an element of the array and performs a test on it that returns a boolean.

For an array of scalar values, this is as simple as el => el === value. For an array of objects, it would be el => el.property === value or el[property] === value.

Hope this helps anybody else curious about this.

How to validate with Yup that in array of objects at least one of object keys has true value?

You could use the test method on yup schema, so your code could be something like this

...
return Yup.object().shape({
question: Yup.string()
.min(QUIZ_QUESTION_MIN_LENGTH, 'Too Short!')
.max(QUIZ_QUESTION_MAX_LENGTH, 'Too Long!')
.required('Required'),
description: Yup.string()
.min(QUIZ_DESCRIPTION_MAX_LENGTH, 'Too Short!')
.max(QUIZ_DESCRIPTION_MIN_LENGTH, 'Too Long!'),
answers: Yup.array().of(answersSchema(rules))
.min(QUIZ_MIN_COUNT_OF_ANSWERS, `The quiz should have a minimum of ${QUIZ_MIN_COUNT_OF_ANSWERS} answers`)
.max(QUIZ_MAX_COUNT_OF_ANSWERS, `The quiz should have a maximum of ${QUIZ_MAX_COUNT_OF_ANSWERS} answers`)
.test('test-name', 'custom error message', answers => {
return answers.some(answer => answer.is_correct)
})
})


as a side note, it is better to use const for declarations that wont change like the variable declarations in the answersSchema function.



Related Topics



Leave a reply



Submit