validates_each designed to validate multiple attributes. In your case, you have one attribute, and you need to check it in your own way.
Do it like this:
class A < ActiveRecord::Base validate :all_emails_are_valid ... private def all_emails_are_valid unless self.email_list.nil? self.email_list.each do |email| if # email is valid -- however you want to do that errors.add(:email_list, "#{email} is not valid") end end end end end
Please note that you can also make a special validator for this or put a check in proc to call validate . See here .
Here is an example with a custom validator.
class A < ActiveRecord::Base class ArrayOfEmailsValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) return if value.nil? value.each do |email| if # email is valid -- however you want to do that record.errors.add(attribute, "#{email} is not valid") end end end end validates :email_list, :array_of_emails => true ... end
Of course you can put the ArrayOfEmailsValidator class in, i.e. lib/array_of_emails_validator.rb , and load it where you need it. Thus, you can use the validator for models or even projects.
source share