如何用 Yup 验证对象数组中至少有一个对象键具有真值?

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

我有一个包含动态字段(答案)的表单。 我正在使用 FormikYup 进行验证。 一个答案是对象 {text: string, is_correct: boolean}。 我需要制作至少一个答案应该有 is_correct: true 的验证模式 在这种情况下如何进行验证?

function answersSchema (rules) {
    const {
        QUIZ_ANSWER_MAX_LENGTH,
        QUIZ_ANSWER_MIN_LENGTH,
    } = rules;
    return Yup.object().shape({
        text: Yup.string()
            .min(QUIZ_ANSWER_MIN_LENGTH, 'Too Short!')
            .max(QUIZ_ANSWER_MAX_LENGTH, 'Too Long!').required('Text of answer is required'),
        is_correct: Yup.boolean().required()
    })
}

export function setQuizSchema(rules) {
    const {
        QUIZ_QUESTION_MAX_LENGTH,
        QUIZ_QUESTION_MIN_LENGTH,
        QUIZ_DESCRIPTION_MAX_LENGTH,
        QUIZ_DESCRIPTION_MIN_LENGTH,
        QUIZ_MAX_COUNT_OF_ANSWERS,
        QUIZ_MIN_COUNT_OF_ANSWERS,
    } = rules;
    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`)
    })
}

您可以在 yup 架构上使用 test 方法,因此您的代码可能是这样的

...
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)
             })
    })
    

作为旁注,最好使用 const 来表示不会像 answersSchema 函数中的变量声明那样更改的声明。