1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

yupで他の値を元に挙動を変更したい

Last updated at Posted at 2022-11-30

何の記事?

yupで他の値を元にバリデーションの挙動を変えたかった。すぐ忘れそうなので覚書として放流🐟

前提条件

例として説明すると以下の型に沿うようなオブジェクトがある。
Settingの使い道は、fullNameとlastName両方の値が入力済みであった場合にのみ、useFullNameをtrueに出来る。といった要件。
逆に言えば、fullNameとlastNameが双方入力されていないとfalseに限定される。

type ProfileType = {
    lastName?: string;
    firstName?: string;
}

type SettingType = {
    useFullName: boolean;
}

実装

サクッと

yup.object().shape({
  firstName: yup.string(),
  lastName: yup.string(),
  useFullName: yup.boolean().required()
    .when(["firstName", "lastName"], {
      // isの戻り値がtrueになった場合にthenが実行される。
      is: (firstName, lastName) => !firstName || !lastName,
      then: yup.bool().oneOf([false], "両方に値必須の助"),
  }),
})

ちなみに、yup.refを使っても別の値の参照はできるっぽい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?