如果其他 3 個欄位中的 1 個不為空,如何使用 Yup 驗證使該欄位成為必填欄位?我嘗試了以下架構,但遇到了回圈依賴問題。謝謝!
const schema = yup.object().shape({
a: yup.string().when(['b', 'c', 'd'], {
is: (b, c, d) => !b && !c && !d,
then: yup.string().required()
}),
b: yup.string().when(['a', 'c', 'd'], {
is: (a, c, d) => !a && !c && !d,
then: yup.string().required()
}),
c: yup.string().when(['a', 'b', 'd'], {
is: (a, b, d) => !a && !b && !d,
then: yup.string().required()
}),
d: yup.string().when(['a', 'b', 'c'], {
is: (a, b, c) => !a && !b && !c,
then: yup.string().required()
})
}, [['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']])
uj5u.com熱心網友回復:
你可以這樣:
a: yup.string().when(['b', 'c', 'd'], { is: (...fields) => fields.some((field) => field === true), then: yup.string().required() }),
您可以使用 JS 的功能,但我選擇了“一些”來檢查陣列中是否至少有一項符合條件,這相當于您的檢查 - 如果陣列中沒有一項為真,那就是都一樣都是假的。
順便說一句,dependencies 陣列是干什么用的?
[['a', 'b', 'c'], ['b', 'c', 'd'], ['a','c', 'd'], ['a','b','d']])
我認為 Yup 官方檔案中沒有提到它(至少我知道是否有理由我很樂意更新,謝謝)。
uj5u.com熱心網友回復:
希望下面的代碼能解決你的問題
/*
All you need to do is list all the pair-wise (2-tuples) combinations.
As you have 4 fields, you expect to have 6 pairs in your array.
i.e. ['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'])
*/
const schema = yup.object().shape({
a: yup.string().when(['b', 'c', 'd'], {
is: (b, c, d) => b || c || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
b: yup.string().when(['a', 'c', 'd'], {
is: (a, c, d) => a || c || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
c: yup.string().when(['a', 'b', 'd'], {
is: (a, b, d) => a || b || d,
then: Yup.string(),
otherwise: Yup.string().required('Required')
}),
d: yup.string().when(['a', 'b', 'c'], {
is: (a, b, c) => a || b || c,
then: Yup.string(),
otherwise: Yup.string().required('Required')
})
}, [['a', 'b'],['a', 'c'],['a', 'd'], ['b', 'c'], ['b', 'd'],['c', 'd'] ])
更多詳情請查看此鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417111.html
標籤:
上一篇:如何使筆畫變圓
