views:

483

answers:

3

I don't understand why the following is not working in Rails 3. I'm getting "undefined local variable or method `custom_message'" error.

validates :to_email, :email_format => { :message => custom_message }

def custom_message
  self.to_name + "'s email is not valid"
end

I also tried using :message => :custom_message instead as was suggested in rails-validation-message-error post with no luck.

:email_format is a custom validator located in lib folder:

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
      object.errors[attribute] << (options[:message] || 'is not valid')
    end
  end
end
A: 

If anyone is interested I came up with the following solution to my problem:

Model:

validates :to_email, :email_format => { :name_attr => :to_name, :message => "'s email is not valid" }

lib/email_format_validator.rb:

class EmailFormatValidator < ActiveModel::EachValidator

  def validate_each(object, attribute, value)
    unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

      error_message = if options[:message] && options[:name_attr]
        object.send(options[:name_attr]).capitalize + options[:message]
      elsif options[:message]
        options[:message]
      else
        'is not valid'
      end

      object.errors[attribute] << error_message
    end
  end
end
Vincent
A: 

Maybe the method "custom_message" needs to be defined above the validation.

Tim