Custom email validation in model - validate domain

11 views
Skip to first unread message

Jake K

unread,
Apr 29, 2012, 4:12:47 PM4/29/12
to Hobo Users
Hi Hoboers,

I'm trying to add a function to my user model that validates the email
address they are signing up with ends in a certain domain. I've added
two things to my model...

1. A function for the actual validation:

def validate_internal_email(email)
domain = email.match(/\@(.+)/)[1] # isolate the domain out of
address
return true if domain.to_s == "hq.example.com"
return false
end

2. A before_create check to run the validation: (Not sure this is the
right approach for what I'm trying to do)

before_create do |user|
if validate_internal_email(:email_address) == false
error-messages.add("Your email must end in hq.example.com")
end
end

Basically the idea is that only users with an
@mysubdomain.mydomain.com can register for an account. Any tips on how
to set this up?

Thanks,
Jake

Matt Jones

unread,
Apr 30, 2012, 8:36:13 AM4/30/12
to hobo...@googlegroups.com
You could use the built-in format validator:

validates :email_address, :format => { :with => /@hq\.example\.com\z/, :message => 'must end in hq.example.com' }

See http://guides.rubyonrails.org/active_record_validations_callbacks.html for more details.

--Matt Jones

Reply all
Reply to author
Forward
0 new messages