What's the best way to validate multiple emails and handle errors in Rails?

久未见 提交于 2019-12-05 20:52:20

Assuming this is a model that has_many emails, and the email model uses :validate_email, you could do something like the following:

class Foo < ActiveRecord::Base
  validate :must_not_have_invalid_addresses

  ...

  def emails=(addresses)
    @invalid_addresses = []
    addresses.split(",").each do |address|
      @invalid_addresses.push(address) unless emails.create({:address => address})
    end
  end

  def must_not_have_invalid_addresses
    errors.add_to_base("Some email addresses were invalid") unless @invalid_addresses.empty?
  end

end

This provides a validation error + an array of the invalid email addresses which you can make accessible to your view if you like.

ruby has a split function (.each) described here and supports regular expressions as described here

as such, you'd split the string (using "," as your separator) and then use the regular expression to validate each e-mail.

You can put saving emails in transaction. Then if any save will fail, then all previos saves are canceled. In such case, validations can be done only on model layer.

I think it would be clear code, but for sure it isn't the fastest possible way (but using Ruby means you are not doing it in even fast way ;) )

If you have them in a variable called emails, perhaps something like this may work:

  if valid_emails?(emails)
      # then have your normal logic here
      if @user.save
           flash[:notice] .....

      end
  end

  private
     def valid_emails?(emails)
        not emails.find {|email| email =~ /[\w\.%\+\-]+@(?:[A-Z0-9\-]+\.)+(?:[A-Z]{2,}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|jobs|museum)/i }.nil?
     end

EDIT: actually you may just want to use this regular expression. It was taken from the restful-authentication plugin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!