so i just started using the custom validators in rails 3, however i am not sure if i can use my existing activerecord i18n locale files. it seems that i have to do
record.errors[attribute] << I18n.t('activerecord.errors.models.{model}.attributes.{attribute}.invalid_whatever') if ...
instead of before when i could have just done
:message => :invalid_whatever
is there shorthand i can use in my ActiveModel:Validator/EachValidator class to accomplish the same thing?
I had the same problem and finally found the answer...
record.errors.add(attribute,:invalid_whatever)
If you end up reading this question (which by the time of this writing is a few years old), you could try the following for Rails 4:
In your model:class Document < ActiveRecord::Base
validates :date, date_in_present: {message: :custom_message}
end
In your validator:class DateInPresentValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
if(value.to_date >= Date.today)
true
else
object.errors[attribute] << options[:message]
end
end
end
In your i18n yml file:en:
activerecord:
errors:
models:
document:
attributes:
date:
custom_message: Date is not in present
I didn't test this thoroughly.
You could also specify a fallback message in the custom validator:object.errors[attribute] << (options[:message] || "Display this message if message is not in options")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With