I wrote a custom validation to error out once a user attempts to withdraw more than the minimum allowed withdrawal amount. The validation fails as it should when the user's withdrawal is below the minimum allowed amount but the code continues running. It does not act like regular validations on model fields.
validate :minimum_withdrawal_amount, on: :create
validates :amount, numericality: {greater_than: 0}
def minimum_withdrawal_amount
if sum.nil? || sum < currency.min_withdraw_amount
errors.add :base, -> { I18n.t('activerecord.errors.models.withdraw.amount.min_withdraw_amount', currency: currency.key, amount: currency.min_withdraw_amount ) }
end
end
It goes ahead and validates the amount that comes after it. If that validation fails, it then errors out. I'll like my custom validation to act like the validation on amount. Hope I'm clear enough
Following replacement might work for you:
errors.add(:base, I18n.t('activerecord.errors.models.withdraw.amount.min_withdraw_amount', currency: currency.key, amount: currency.min_withdraw_amount ))
Related
I have several validations that validate a Quote object. Upon validation, I have a before_save callback that calls an API and grabs more data, makes a few math computations and then saves the newly computed data in the database.
I don't want to trust the API response entirely so I need to validate the data I compute.
Please note that the API call in the before_save callback is dependent on the prior validations.
For example:
validates :subtotal, numericality: { greater_than_or_equal_to: 0 }
before_save :call_api_and_compute_tax
before_save :compute_grand_total
#I want to validate the tax and grand total numbers here to make sure something strange wasn't returned from the API.
I need to be able to throw a validation error if possible with something like:
errors.add :base, "Tax didn't calculate correctly."
How can I validate values that were computed in my before_save callbacks?
you can use after_validation
after_validation :call_api_and_compute_tax, :compute_grand_total
def call_api_and_compute_tax
return false if self.errors.any?
if ... # not true
errors.add :base, "Tax didn't calculate correctly."
end
end
....
Have you tried adding custom validation methods before save? I think this is a good approach to verify validation errors before calling save method
class Quote < ActiveRecord::Base
validate :api_and_compute_tax
private
def api_and_compute_tax
# ...API call and result parse
if api_with_wrong_response?
errors.add :base, "Tax didn't calculate correctly."
end
end
end
Then you should call it like
quote.save if quote.valid? # this will execute your custom validation
I have a form for my Subscription model and users have the option to enter a phone number. The Twilio API is being used.
class Subscription < ActiveRecord::Base
validates_numericality_of :phone_number, allow_blank: true
validate :mobile_phone_number
def mobile_phone_number
lookup_client = Twilio::REST::LookupsClient.new Rails.application.secrets.twilio_sid, Rails.application.secrets.twilio_token
begin
response = lookup_client.phone_numbers.get("#{self.phone_number}")
response.phone_number #if invalid, throws an exception. If valid, no problems.
return true
rescue => e
errors.add(:base, "That phone number is not valid.")
end
end
What is occurring: I can only enter valid phone numbers given the Twilio lookup API...this is a good thing. However, users need to be able to enter a BLANK phone number.
Currently, the validates_numericality_of method is getting overwritten by the mobile_phone_number method.
If I enter a blank phone_number, "That phone number is not valid" gets returned. This should not be happening.
How do I make a special case for the rescue? For example, "rescue this unless phone number is blank". Or what am I doing wrong here?
All input is appreciated.
This way you won't even enter your validating function.
Take a look at conditional validations
validate :mobile_phone_number, unless: proc { phone_number.blank? }
for those who dont like unless
validate :mobile_phone_number, if: proc { phone_number.present? }
At the beginning of the begin:
if self.phone_number.blank?
return true
end
I have a conditional form field (which is shown by clicking a checkbox) which I want to validate with a custom method.
validates :number, length: { maximum: 20 }, if: :checksum_is_valid?
def checksum_is_valid?
if !Luhn.valid?(number)
errors.add(number, "is not valid.")
end
end
is my attempt. This technically works fine but the error is also shown, even if I don't enter any number at all (because the field is not mandatory). Any idea how I can check with a custom method, but only if the user provides any number at all.
Thanks
You could use validate instead of validates for custom validators and then move the check if there is a number present into the validator method:
validate :checksum_valid?
private
def checksum_valid?
if number.present?
errors.add(:number, "is not valid.") unless number_valid?
end
end
def number_valid?
number.length < 20 && Luhn.valid?(number)
end
You're mixing two things in your code, so let me help you understanding better what is happening.
1). conditional validation:
validates :number, length: { maximum: 20 }, if: :checksum_is_valid?
By this, Rails expects the model to implement method checksum_is_valid? which returns boolean value, based on which it will perform this validation. Something like would work:
def checksum_is_valid?
Luhn.valid?(number)
end
In case this method returns true, Rails would perform the validation of :number is not more than 20.
2). custom validation:
When using this custom method, you can build your own validation logic and error. So, if you have your method:
def checksum_is_valid?
if !Luhn.valid?(number)
errors.add(number, "is not valid.")
end
end
You should configure your validator with:
validate :checksum_valid?
Unfortunately, from your code is not clear what you would like to achieve (validate the number not to be more than 20, or perform the custom validator), but I hope what I've pointed will help you make the proper decision how to take that further.
Hope that helps!
How to distinct which validator failed ?
I have multiple validations on the same field:
class User < ActiveRecord::Base
validates :name, presence: true, length: {minimum: 1, maximum: 20 }
validates_uniqueness_of :name
end
When I save the user as user.save - I want to distinct what failed.
if user.__not_valid_name_length__?
# name length wrong
# do smth 1
end
if **user.__not_valid_name_unique__?
# name is not unique
# do smth 2
end
I can access user.errors[:name] and see all error messages for the field.
But I don't want to rely on message text which can change.
Is there any way to know which validator failed?
A feature to return machine-parseable symbols instead of strings was committed to Rails almost a year ago, but it's still not available in the 4-x-stable branch. You can use it if you use the edge version, and it will be available in Rails 5.
Example:
user = User.new
user.valid?
user.errors.details[:name] # returns: [{error: :blank}, {error: :too_short}]
More info:
https://github.com/rails/rails/pull/18322
https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb
There are no built-in callbacks for rails validation fails, for rails validation available callbacks are:
before_validation
after_validation
To learn more about callback, please read this call_back
Checking validation fail base on the message is no good approach. It may change in different scenarios i.e internationalization. Do it by defining the method for validation i.e
# check presence_of validation
def is_name_present?
self.name.present?
end
# check uniqueness validation
def is_name_uniqe?
User.where(name: self.name).count == 0
end
Use one which suit you best, I suggest use after_validation
after_validation :post_validatiom
def post_validation
unless is_name_present?
# do_someting
end
unless is_name_uniqe?
# do_something
end
end
In an multilingual application, a user can input their Chinese and English names. The user can input either or both, but must input at least one name.
class Person < ActiveRecord::Base
validates :zh_name, :presence => true
validates :en_name, :presence => true
validates :fr_name, :presence => true
end
Since the built-in :validates_presence_of method can only validate both attributes at once, is there a way to validate the presence of at least one of many attributes in rails?
Like a magical, validates_one_of :zh_name, :en_name, :fr_name
Thank you in advance,
validate :at_least_one_name
def at_least_one_name
if [self.zh_name, self.en_name, self.fr_name].reject(&:blank?).size == 0
errors[:base] << ("Please choose at least one name - any language will do.")
end
end
Taking #micapam's answer a step futher, may I suggest:
validate :has_a_name
def has_a_name
unless [zh_name?, en_name?, fr_name?].include?(true)
errors.add :base, 'You need at least one name in some language!'
end
end
just a quick shot out, you can pass a "if" or "unless" to the validator, maybe you can get it working this way. i have something like this in mind
validates :zh_name, :presence => { :if => (fr_name.blank? && en_name.blank?) }
validate :has_a_name
def has_a_name
unless [zh_name, en_name, fr_name].any?{|val| val.present? }
errors.add :base, 'You need at least one name in some language!'
end
end
Max Williams' answer is fine, but I didn't see the need to count hits when any? returns a boolean.