Add custom validation block error on a field

Hi :slight_smile:

I’m using dry-validation to validate the parameters for an API, and I’d like to know if there’s a way to add custom validation block errors to a field. For example:

UserSchema = Dry::Validation.Params do
  configure do
    option :ids

    def self.messages
      super.merge(
        en: { errors: { valid_id: 'id is not valid' } }
      )
    end
  end

  required(:id).filled(:int?)

  validate(valid_id: :id) do |id|
    ids.include?(id)
  end
end

schema = UserSchema.with(ids: [1, 2, 3])

schema.(id: 4).errors

# current behaviour
# => {:valid_id=>["id is not valid"]}

# wanted behaviour 
# => {:id=>["id is not valid"]}

hey!

So => en: { errors: { id: 'id is not valid' } } will do the trick.

If I do that, I’ll get this error message for valid_id was not found

Ah sorry, you also need to define the rule like this: validate(id: :id) do..end. That’s a weird limitation, I know.

Ah… So if I have 2 validate on the same field, this won’t work :frowning:

Actually, IIRC it will work with multiple blocks. Please try.

UserSchema = Dry::Validation.Params do
  configure do
    option :ids

    def self.messages
      super.merge(
        en: { errors: { id: 'id is not valid' } }
      )
    end
  end

  required(:id).filled(:int?)

  validate(id: :id) do |id|
    ids.include?(id)
  end
end

schema = UserSchema.with(ids: [1, 2, 3])

puts schema.(id: 4).errors