On Jan 21, 12:05 am, CuriousNewbie <bhellm...@gmail.com> wrote:
> Hello, I'm working to create a method in my controller to check an
> email to see if the email's domain is acceptable. I want to prevent
> gmail and hotmail for certain reasons. Here's what I have so far:
>
> controller:
>     if valid_email_domain(email_address)
>       # good email domain
>     else
>       # bad email domain
>     end
>
> protected
>   def valid_email_domain(emailAddy)
>     reg = Regexp.new '/#{User::INVALID_EMAILS.map{|a|
> Regexp.quote(a)}.join("|")}/'
>     return true if emailAddy.scan(reg).size == 0
>   end
>
> user model:
> INVALID_EMAILS = %w(gmail.com hotmail.com)
>
> But that errors, any ideas? I'm not sure if I'm doing the REGEX
> correctly, could use some regex help.

First, I agree with Marnen that this should be done in the model but I
disagree that the regexp is formed correctly on a very minor point;
you don't need to add the '/' inside the quotes when building a new
regexp object i.e. Regexp.new('some regexp') rather than Regexp.new('/
some regexp/').

So what I would do in the model is:

class User < AR::B
  INVALID_EMAILS = %w(gmail.com hotmail.com)
  def self.valid_email?(email)
     reg = Regexp.new(INVALID_EMAILS*'|') # *'string' is an alias
for .join('string') use whichever you preffer
     matches = reg.match(email)
     return matches == 0
  end
end

Then in the controller you can do

def some_action
  if User.valid_email?(params[:email])
    #do stuff
  else
    #do other stuff
  end
end

This has the added benefits that you can use this same validation
anywhere in your code and easily add additional conditions to your
validation in a single place.

-T

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to