Skip to content

Instantly share code, notes, and snippets.

@timriley timriley/example.rb
Created Jan 10, 2017

Embed
What would you like to do?
Example of dry-validation predicate for "unique within some scope"
UserSchema = Dry::Validation.Schema do
configure do
# Hard-coding the custom error messages
def self.messages
Dry::Validation::Messages.default.merge(
en: {errors: {unique_within_account?: 'is not unique within this account'}}
)
end
# Here's the custom predicate
def unique_within_account?(account_id, user_name)
# Faking this out here. IRL you'd use an injected option or a hard-coded
# lookup to some account/user data.
!user_name.include?(account_id.to_s)
end
end
required(:account_id).filled(:int?)
required(:name).filled
rule(name: [:account_id, :name]) do |account_id, name|
name.unique_within_account?(account_id)
end
end
valid_input = {account_id: 1, name: "my_name"}
# UserSchema.(valid_input)
# => #<Dry::Validation::Result output={:account_id=>1, :name=>"my_name"} errors={}>
invalid_input = {account_id: 99, name: "my_name_99"}
UserSchema.(invalid_input)
# => #<Dry::Validation::Result output={:account_id=>99, :name=>"my_name_99"} errors={:name=>["is not unique within this account"]}>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.