generated at
Yupで両方必須か両方空のみを許容する


ts
import * 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


ポイントは、yup.object.shapeの第2引数のnoSortEdgesを指定しているところ
docsに全く説明がない
when などを使う時に、相互依存がある場合に、これを指定しないといけない
ここに説明がある
めちゃくちゃバグりやすく、安全でない実装なので、敢えてdocsに書いていないっぽい
安全じゃないからこそ、docsに書くべきだとも思うけどmrsekut