LoginSignup
0
1

More than 3 years have passed since last update.

ネストしたオブジェクトをYupでバリデーションする

Posted at

Railsでいうnested attributesみたいなやつ :bulb:

{
  "title" => "title dayo",
  "body" => "body dayo",
  "tag_attributes" => {
    "0" => { "name" => "hoge" },
    "1" => { "name" => "fuga"}
  }
}

Yup.lazyとlodashのmapValuesを使いました。

import * as Yup from "yup";
import mapValues from "lodash.mapvalues";

interface Form {
  title: string;
  body: string;
  tag_attributes: {
    [key: string]: {
      name: number;
    };
  };
}

const validationSchema = Yup.object().shape({
  title: Yup.string(),
  body: Yup.string(),
  tag_attributes: Yup.lazy<object>(obj =>
    Yup.object(
      mapValues(obj, () =>
        Yup.object().shape({
          name: Yup.string()
        })
      )
    )
  )
});

以上です :hugging:

参考

0
1
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
0
1