gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:17:04 25 4
gpt4 key购买 nike

我有一个带有动态字段(答案)的表单。
我正在使用 福米克 是的用于验证。
一个答案是对象 {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`)
})
}

最佳答案

您可以使用 test yup 模式上的方法,所以你的代码可能是这样的

...
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 中的变量声明功能。

关于javascript - 如何使用 Yup 验证对象数组中至少一个对象键具有真实值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62931332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com