Reputation: 41
I've been trying to validate a sign in process using Hanami (which is on top of dry-validation).
The point is: how to validate someting related to 2 fields: email + password?
I've read about custom predicates, but they seem to be only per field. Another concept is rule, but according to the examples it doesn't relate 2 things the way I need.
Here is my code:
module Web::Controllers::Sessions
class Create
include Web::Action
expose :validation # my standard way to show errors in the template
def call(params)
@validation = SigninValidator.new(params[:user]).validate
if @validation.success?
# more stuff here
end
end
end
class SigninValidator
include Hanami::Validations::Form
validations do
required(:email) { format?(EMAIL_REGEX)}
required(:password).filled(:str?)
# I GOT CONFUSED HERE
# how could I use someting like a repository and relate something like
# predicate + message for "email or password doesn't match"
end
end
Unfortunately the validations section in Hanami Guide is empty and I couldn't find a solution looking at the sources (hanami-validation and dry-validation).
Any help would be appreciated.
Upvotes: 4
Views: 1064
Reputation: 1160
I don't fully understand what you're trying to achieve, it seems as though you're attempting to validate whether the email and/or password match the ones in your database? If so then you're doing it in the wrong place, validators are intended to validate the params only. So if the email is in the wrong format, or the password and password confirmation don't match, a validation can catch that and provide the right error message. If you're looking to verify details against the database then this is something that should be done in the interactor.
m45t3r is correct in saying that if you do want to validate two dependent attributes then a rule is probably the way to go.
As for your broken link, the Hanami guides got moved a while back and the old links don't seem to have been forwarded too well! The current docs for validations, and specifically rules, can be found here.
Upvotes: 0
Reputation: 457
You can use either High-Level Rules or Custom Validation Blocks. Something like this:
validations do
required(:email) { format?(EMAIL_REGEX)}
required(:password).filled(:str?)
rule(:email_and_password: [:email, :password]) do |email, password|
# Example, do what you need here
# Only dry-rb rules are valid here
email.filled? & password.filled?
end
# Or
validate(:email_and_password: [:email, :password]) do |email, password|
# Example, do what you need here
# Any Ruby code is valid here
email.filled? && password.filled?
end
end
Maybe you will need to set :email
and :password
to optional here, and ensure they're filled inside rule
or validate
block.
Upvotes: 3