Closed schorsch closed 10 years ago
I like the idea, but IMHO the code can be improved: A Validator allows the attribute name to be dynamic. validates_with
can take an option hash.
Example:
class IBANValidator < ActiveModel::Validator
def validate(record)
field_name = options[:field_name] || :iban
value = record.send(field_name)
unless IBANTools::IBAN.valid?(value.to_s)
record.errors.add(field_name, :invalid)
end
end
end
...
class User
# Validate the attribute "iban_the_terrible" as IBAN
validates_with SEPA::IBANValidator, :field_name => :iban_the_terrible
end
Added some changes. IMHO this handles better custom names in the database schema
so one can use them in their own models for field validation