Hi All,
I’m using dry-validation
to validate the parameters for an API, and I am curious to understand how can I add a rule or validation to a field on a nested data schema.
For example:
API::V2::AppointmentSchema = Dry::Validation.Schema(API::V2::BaseSchema) do
TYPE ||= %w(sms voice).freeze
required(:appointment).schema do
required(:type, :string).filled(:str?, included_in?: TYPE)
optional(:reminders, :array).each do
schema do
optional(:send_time, [nil, :string]).maybe(:str?, format?: FormatConstants::ISO8601_TIME)
optional(:num_of_days_before, [nil, :integer]).maybe(:int?, gteq?: 0, lteq?: 30)
required(:immediate, :integer).filled(:bool?)
rule("reminders.immediate_false": [:immediate, :num_of_days_before, :send_time]) do |immediate, num_of_days_before, send_time|
immediate.false?.then(num_of_days_before.filled? & send_time.filled?)
end
rule("reminders.immediate_true": [:immediate, :num_of_days_before, :send_time]) do |immediate, num_of_days_before, send_time|
immediate.true?.then(num_of_days_before.none? & send_time.none?)
end
end
end
end
end
This code returns:
appointment=>{:“reminders.immediate_false”=>[“must be filled”], :“reminders.immediate_true”=>[“cannot be defined”]}>
I wish we could add those specific error messages to fields or at least nest them under the nested data(in that case :reminders)
How can we accomplish this?