Yupで両方必須か両方空のみを許容する
例
tsimport * as yup from "yup";
const schema = yup.object().shape(
{
a: yup
.string()
.max(10)
.when("b", {
is: (b) => b != null,
then: yup.string().required("両方の項目を埋めてください")
}),
b: yup
.string()
.max(10)
.when("a", {
is: (a) => a != null,
then: yup.string().required("両方の項目を埋めてください")
})
},
[["a", "b"]]
);
console.log("=====================================");
console.log(`両方入力: ${schema.isValidSync({ a: "hoge", b: "piyo" })}`); // true
console.log(`aが空 :${schema.isValidSync({ a: undefined, b: "piyo" })}`); // false
console.log(`bが空 :${schema.isValidSync({ a: "hoge", b: undefined })}`); // false
console.log(`両方空 :${schema.isValidSync({ a: undefined, b: undefined })}`); // true
when
などを使う時に、相互依存がある場合に、これを指定しないといけない
めちゃくちゃバグりやすく、安全でない実装なので、敢えてdocsに書いていないっぽい
安全じゃないからこそ、docsに書くべきだとも思うけど
