LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby】dry-validationでバリる

Posted at

概要

Validationを良い感じにやってくれるgemを現在使っているため備忘録として記事を書いていく。
ここでは特にdry-validationdry-strcutを解説!

使うまでの流れ

1.Gemをインストール

$ gem install dry-validation
$ gem install dry-struct

2.基底クラスを作成

class ApplicationContract < Dry::Validation::Contract
  config.messages.default_locale = :ja # デフォルトメッセージを日本語に変換
  config.messages.backend = :yaml
  config.messages.load_paths << 'config/contract/error.yaml' # 任意のエラーメッセージを書くロケールファイルのpath
  EMAIL = /.@./ # メールバリデーション用
  PHONE_NUMBER = /\A[0-9+\-]+\z/ # 電話番号バリデーション用
end
class Struct < ::Dry::Struct
  module Types
    include ::Dry.Types()
  end
end

3.ロケールファイルを作成する

ja:
  dry_validation:
    errors:
      sample: 'エラーです'

dry-validation編

実際の定義方法

class Sample < ApplicationContract
  # 渡ってきたパラメーターをチェック
  params do
    required(:sample1).filled(:string) # sample1カラムは必須でstring型かどうかチェック
    required(:sample2).maybe(:string) # sample2カラムは必須で値が入っている場合はstring型かどうかチェック
    optional(:sample3).filled(:integer) # sample3は必須でなくてinteger型かどうかチェック
    required(:sample4).value(:string) # 厳密にstring型かどうかをチェック
  end

  # 自分好みなバリデーションチェック
  rule(:sample5) do
    if sample5
      key(:sample5).failure('サンプルエラー')
    end
  end
end

dry-strcut編

実際の定義方法

class Sample < Struct
  attribute :sample1, Types::String # string型で定義
  attribute :sample2, Types::Strict::String # string型で定義し間違ったタイプの値が渡されるエラーを起こす
  attribute :sample3, Types::Coercible::Integer # 強制メソッドを使用して属性を正​​しい型(integer)に変換
  attribute :sample4, Types::Params::Date['2022-4-8'] # HTTPパラメータ用の型
  attribute :sample5, Types::Params::Date['2022-4-8'] # HTTPパラメータ用の型
end

参考

dry-rb/dry-validation
dry-rb/dry-struct
Rubyでvalidationするdry-validationの基本のキ
dry-struct
dry-types
dry-rb/dry-structメモ
dry-rb/dry-typesメモ

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