2

http://api.rubyonrails.org/classes/ActiveModel/Validations.html

How would you change the validation message? If I wanted to make it give back a pirate message.

Like this:

validates_presence_of  :blank (“can’t be blank”)  

would instead be:

validates_presence_of  :blank (“can’t be blank, walk the plank“)  

Further more if I wanted to run a script on all the error messages to add a funny word to each message without doing each individually; How would you suggest doing that? I want to do them for all the validations below.

ActiveModel::Validations

activemodel/lib/active_model/validations.rb  
activemodel/lib/active_model/validations/absence.rb  
activemodel/lib/active_model/validations/acceptance.rb  
activemodel/lib/active_model/validations/callbacks.rb  
activemodel/lib/active_model/validations/clusivity.rb  
activemodel/lib/active_model/validations/confirmation.rb  
activemodel/lib/active_model/validations/exclusion.rb  
activemodel/lib/active_model/validations/format.rb  
activemodel/lib/active_model/validations/inclusion.rb  
activemodel/lib/active_model/validations/length.rb  
activemodel/lib/active_model/validations/numericality.rb  
activemodel/lib/active_model/validations/presence.rb   
activemodel/lib/active_model/validations/validates.rb  
activemodel/lib/active_model/validations/with.rb

It seems I would use: http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html

class Comment
  include ActiveModel::Validations

  validate do
    errors.add(:base, 'Must be friends to leave a comment') unless   commenter.friend_of?(commentee)
  end
end

Any other tips or suggestions?

jendiamond
  • 69
  • 7

1 Answers1

0

For custom validations I've been using this with I18n. I believe it should work the same way for normal messages

# models/user.rb
validate :some_validation

def some_validation
  errors.add(:base, :custom_validation_translation_sym)
end

# config/locales/en.yml (examplewith mongoid)
mongoid:
    errors:
      models:
        user:
          attributes:
            base:
              custom_validation_translation_sym: Your translation goes here !

add a funny word to each message without doing each individually

  1. You could override the ActiveModel handling the errors strings
  2. In your views, when you show model errors, nothing prevents you from playing with the strings

    <% @model.errors.full_messages.each do |msg| %>
    
    <%= "Funny string"+msg %>
    
    <% end %>
    
Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164