e.g.: comma seperated in a single textfield: [email protected], mail2@someotherdomain, ...
Look at ActiveRecord::Validations::ClassMethods, specifically the validates_each method.
http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002161
This will let you pass the attribute as a block and then you can write your own validation method that will split your string and validate each email address to a regular expression.
You can use the TMail::Address module to validate an email as shown here. Custom validations can be added with the validate
method.
validate :check_email_addresses
def check_email_addresses
email_addresses.split(/,\s*/).each do |email|
TMail::Address.parse(email)
end
rescue TMail::SyntaxError
errors.add(:email_addresses, "are not valid")
end
Update: The TMail::Address module seems to be too lax on what is considered a valid email address (see comments below) so instead you can use a regular expression.
validate :check_email_addresses
def check_email_addresses
email_addresses.split(/,\s*/).each do |email|
unless email =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
errors.add(:email_addresses, "are invalid due to #{email}")
end
end
end
There are a variety of regular expression solutions for validating an email address. See this page for details.
If anyone is trying to parse an address list with names in it, as may appear in an email header, the easiest way I found to do that is:
header = TMail::HeaderField.new('to', address_list_string)
header.addrs
will then contain an array of TMail::Address
objects, which you can access for the name, email address, domain, etc.