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

概要

ZIO Schemaは、スキーマ定義ライブラリです。
本記事では、Schema#validate メソッドに焦点を当て、データ検証を行う方法を解説します。

Schema#validate とは?

Schema#validate は、特定のスキーマに対して値を検証し、その結果を Chunk[ValidationError] として返すメソッドです。検証は、スキーマに定義された型情報や制約に基づいて行われます。

サンプルコード

下記の例では、Person スキーマに age が 18 歳以上であるという制約を設け、validate メソッドで検証しています。
有効な値の場合は空の Chunk が返されます。

import zio.*
import zio.schema.*
import zio.schema.validation.*

object Main extends ZIOAppDefault {
  case class Person(name: String, age: Int)

  object Person {
    implicit val schema: Schema[Person] = Schema.CaseClass2[String, Int, Person](
      id0 = TypeId.fromTypeName("Person"),
      field01 = Schema.Field(
        "name",
        Schema[String],
        get0 = _.name,
        set0 = (person, newName) => person.copy(name = newName)
      ),
      field02 = Schema.Field(
        "age",
        Schema[Int],
        get0 = _.age,
        set0 = (person, newAge) => person.copy(age = newAge),
        validation0 = Validation.greaterThan(17)
      ),
      construct0 = (name, age) => Person(name, age)
    )
  }

  val validPerson = Person("Alice", 30)
  val invalidPerson = Person("Bob", 15) // 18歳未満のため無効

  val result1: Chunk[ValidationError] = Person.schema.validate(validPerson)
  val result2: Chunk[ValidationError] = Person.schema.validate(invalidPerson)

  override def run: ZIO[ZIOAppArgs, Any, Any] = Console.printLine(
    (
      Person.schema.validate(validPerson),
      Person.schema.validate(invalidPerson)
    )
  ) // (Chunk(),Chunk(GreaterThan(15,17)))
}

検証ルールの定義

ZIO Schema は、様々な検証ルール (Validation) を提供しています。

  • Validation.minLength(s): 文字列長の最小値
  • Validation.maxLength(s): 文字列長の最大値
  • Validation.regex(regex): 正規表現
  • Validation.greaterThan(n): 数値の下限
  • Validation.lessThan(n): 数値の上限

これらのルールを組み合わせることで、複雑な検証ルールも表現できます。

まとめ

Schema#validateにより、データ検証を簡潔に行うことができました。

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