Add custom validation block error on a field


#1

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"]}

#2

hey!

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


#3

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


#4

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


#5

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


#6

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


#7
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