Question

I'm currently trying to validates an email attributes with few things :

  1. Its presence
  2. Its format with a regex
  3. Its uniqueness
  4. Its non presence in a list of mail providers

I'm stuck at the fourth step, I don't really know how to implement it, the main of this steps is to exclude throwable mail providers.

I've currently this :

  validates :email, :presence   => true,
                    :format     => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false },
                    :exclude => Not working when I put a regex here

My problem isn't the regex, it's how to exclude email matching with exclude regex.

Can you help me do this ?

Cordially, Rob.

Was it helpful?

Solution

If you use devise for user authentication you can uncomment code in devise.rb

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  # config.email_regexp = /\A[^@]+@[^@]+\z/

otherwise i think you can write like

in model

  validates :email, uniqueness: true
  validate  :email_regex

 def email_regex
    if email.present? and not email.match(/\A[^@]+@[^@]+\z/)
      errors.add :email, "This is not a valid email format"
    end
  end

OTHER TIPS

The format validator has a without option (at least in rails 4 and 3.2), so...

validates :email, :presence   => true,
                  :format     => { :with => email_regex},
                  :uniqueness => { :case_sensitive => false }
validates :email, :format     => {:without => some_regex}

Rails provides exclusion helper, not exclude; anyway, it validates that the attributes' values are not included in a given set. (http://guides.rubyonrails.org/active_record_validations.html#exclusion)

I think you should use custom validation method to solve your problem (http://guides.rubyonrails.org/active_record_validations.html#custom-methods).

Do something like this in your model.

validate :exclude_emails

private

def exclude_emails
if ( self.email =~ /blah(.*)/ )
  errors.add_to_base("Email not valid")
end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top