Add custom validation block error on a nested data field

#1

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?

0 Likes

#2

This will be supported in 1.0.0.

0 Likes

#3

@solnic what is the release timeline for 1.0.0? Do we have this already?

0 Likes

#4

The first beta of 1.0.0 will be released next week. Then it will depend on testing results. I suspect we will manage to release the final version in the first weeks of April.

0 Likes