Localizable Rails 3 validators
Rails 3 introduced a new style of validators that allow us to group validations for each attribute into their own line. It also became easy to create our own, custom validators.
This a small tip, perhaps even a best practice, when doing so.
Most the examples I’ve seen around the web ends up adding errors to the errors array using something like
record.errors[attribute] << (options[:message] || "is not valid")
Unfortunately doing it this way means your validator doesn’t behave like the standard validators and the error message cannot be localized.
Instead, please use
record.errors.add(attribute, (options[:message] || :invalid))
Using a Symbol rather than a String lets you localize the validation message via your standard Rails I18n mechanism. It also lets you pass a proc to :message, allowing for things like Time.now
to be used within an error message.
Thank you in advance from those of us who create non-English apps.