gpt4 book ai didi

javascript - 使用 Yup 访问必填字段

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

我使用 react-hook-form 和 yup 来验证我的表单。

我想知道架构的所有必填字段以在表单中显示一些信息(如必填字段的“*”)。我们可以通过这行代码实现这一点:

schema.describe().fields[field].tests.findIndex(({ name }) => name === 'required'

但是,此代码不适用于条件验证。

架构示例:

const schema = yup.object().shape({
email: yup
.string()
.email()
.required(),

isProfileRequired: yup
.boolean(),

profile: yup
.object()
.when('isProfileRequired',{
is: (isProfileRequired) => isProfileRequired,
then:
yup
.object()
.nullable()
.required()
})
})

有没有办法在表单中检索这些信息?

最佳答案

实际上没有“好”的方法可以做到,但这很有效:

function isRequired(field){
return schema.fields[field]._exclusive.required || false
}

注意:schema.fields[field]._exclusive.required 如果需要或未定义,则返回 true。

关于javascript - 使用 Yup 访问必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64440400/

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