AnApprentice
AnApprentice

Reputation: 110960

Rails - Validating a list of emails in the controller

I'm trying to create a form where a user can enter a list of emails to send out invitations using Devise Invitable.

Here is my controller which works with valid emails:

def create

  params[:user][:email].split(/, ?/).each do |email|
    params[resource_name][:email] = email
    self.resource = resource_class.invite!(params[resource_name].merge(:invited_by => current_user.instance_id))
  end

  respond_to do |format|
    if resource.errors.empty?
      format.js { render :template => 'devise/invitations/create' }
    else
      format.js { render 'devise/invitations/errors', :notice => resource.errors }
    end
  end
end

My end goal while looping through all the emails. Do the following:

  1. Valid the email is valid before queuing on the mail server
  2. Keep a list of all the invalid emails, so we can let the user know and give them a chance to fix and resubmit

Suggestions on how to do this type of email validation while storing any invalid records to be sent back?

Thanks

Upvotes: 1

Views: 983

Answers (1)

Raghu
Raghu

Reputation: 2563

Here is a little piece of code that I had written a couple of months ago to validate a list of emails(Comma separated) and filter the list of emails and separate the invalid emails from the valid ones . This code is tested using rspec

def parse_emails(emails)
    valid_emails, invalid_emails = [], []
    unless emails.nil?
      emails.split(/,|\n/).each do |full_email|
        unless full_email.blank?
          if full_email.index(/\<.+\>/)
            email = full_email.match(/\<.*\>/)[0].gsub(/[\<\>]/, "").strip
          else
            email = full_email.strip
          end
          email = email.delete("<").delete(">")
          email_address = ValidatesEmailVeracityOf::EmailAddress.new(email)
          if email_address.pattern_is_valid?
            valid_emails << email 
          else
            invalid_emails << email
          end
        end
      end                    
    end
    return valid_emails, invalid_emails
  end

Feel free to refactor this .

I am using the validates_email_veracity_of plugin that makes this job a little more easier and adds to stronger validation. Add this line in the top of your model

validates_email_veracity_of :email_address, :domain_check => false, 
                                      :message => 'is invalid for one of your invitations.  Please review what you have entered.',
                                      :timeout => 1 # => Time in seconds.

Upvotes: 2

Related Questions