简体   繁体   中英

Rails 3: Custom error message in validation

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

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

Just for reference, this is what I believe is going on. The 'validates' method is a class method, ie MyModel.validates(). When you pass those params to 'validates' and you call 'custom_message', you're actually calling MyModel.custom_message. So you would need something like

def self.custom_message
  " is not a valid email address."
end

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

with self.custom_message defined before the call to validates.

也许需要在验证之上定义“custom_message”方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM