Reputation: 3025
I am trying to add a validation to a simple form in a Rails 4.1 project. I need to reject a form submission if a text field contains a forbidden word. My other validations work but not this one. So if the user enters no value or too long of a value it is rejected and the error message is displayed.
I have it setup similarly to the edge guide (http://edgeguides.rubyonrails.org/active_record_validations.html#exclusion) but the form submit still goes through if I enter "My favorite color is red." What should I do differently?
My model:
class ColorEntry < ActiveRecord::Base
validates :body, presence: true
validates :body, length: { maximum: 255 }
validates :body, exclusion: { in: %w(red) }
end
Upvotes: 1
Views: 1174
Reputation: 335
Try to use a regex validation for format with the "without" attribute. So, if it does not match, the form can't be submitted.
validates :body, format: {without: /example/}
Other syntax
validates_format_of :body, without: /example/
More references in:
http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html
Upvotes: 5