3

I am building a long list of terms I would like to prevent from entry into a field using validates_exclusion_of. This list is getting very long, and some of the terms in it may be inappropriate/offensive/distracting/procrastination-inducing for other programmers. Is there a way to connect the following code to a separate plain text document held somewhere on my repo?

validates_exclusion_of :path, :in => %w( long list of bad words ... ), :message => "This is a protected word. Please try another."

Bonus: this message doesn't display on my form when a user enters one of these terms. How do I get the message to display?

sscirrus
  • 55,407
  • 41
  • 135
  • 228

2 Answers2

6

you don't have to use validates_exclusion_of you can just define your own validate

validate :check_bad_words

def check_bad_words
  @bad_words ||= File.read('badwords.txt').split
  errors.add_to_base("#{path} is a protected word. Please try another.") if @bad_words.include? path
end

for your error message to show up on the form, in older rails it is
<%= f.error_messages %> where f is the form

for rails 3.x i think you have to do it yourself as per f.error_messages in Rails 3.0

Community
  • 1
  • 1
Kalendae
  • 2,256
  • 1
  • 21
  • 23
0

To display the message you need in your form something like this (haml example)

- if @object.errors.any?
  #error_explanation= error_messages_for :object
codevoice
  • 474
  • 3
  • 6