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
Allowing/Replacing Comma as Number Separator for Input Type="Number" Using Rails
How to Get Public User All Posts from Instagram, Without Instagram API
Typescript | Warning About Missing Return Type of Function, Eslint
Remove the Default Browser Header and Footer When Printing HTML
Blocking Device Rotation on Mobile Web Pages
How to Run HTML File on Localhost
How to Mock Private Functions With Jest
How to Prevent Form to Reload Page After Onsubmit
Html Input File Selection Event Not Firing Upon Selecting the Same File
Transforming Null into Empty String in JavaScript
How to Allow Only English Letters in Input Fields
Typeerror: Data.Foreach Is Not a Function
React - How to Add Dynamic Key/Value Pair to an Object
Make an Angular *Ngfor Draw Two Different Columns of Data
Json Object Array Inside Array Find and Replace in JavaScript