abpetkov
abpetkov

Reputation: 914

Require and validate email conditionally based on the existence of another field

I'm allowing the email to be optional sometimes, depending on whether there is a phone field or not. If there is such - do not validate for presence, if there is not - validate it. Here's the code:

# model.rb
validates :email, length: {maximum: 255},
        uniqueness: {case_sensitive: false},
        email: true

validates_presence_of :email, unless: Proc.new {|user| user.phone? }

The problem is the way this is, if the user submits an empty email field, it will error with Email has already been taken and Email is not an email.

I also have an email_validator.rb:

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    unless value =~ MY_EMAIL_REGEX
      record.errors.add(attr_name, 'is not an email')
    end
  end
end

I want to:

Upvotes: 1

Views: 166

Answers (1)

Gagan Gami
Gagan Gami

Reputation: 10251

You have used Proc in one validation of email but not in other validation, use in both :

validates :email, length: {maximum: 255},
        uniqueness: {case_sensitive: false},
        allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string
        email: true, unless: Proc.new {|user| user.phone? }

validates_presence_of :email, unless: Proc.new {|user| user.phone? }

You can merge both validation like this:

validates :email, length: {maximum: 255},
           uniqueness: {case_sensitive: false},
           presence: true,
           allow_blank: true, # This option will let validation pass if the attribute's value is blank?, like nil or an empty string  
           email: true, unless: Proc.new {|user| user.phone? }

Upvotes: 1

Related Questions