hiho
Is there any way to tell rails that my string may not be 'something'?
I am searching for something like
validates :string, :not => 'something'
thanks klump
Either of these will do the job (click on the methods for documentation):
Probably the best and fastest way, easy to extend for other words:
validates_exclusion_of :string, :in => %w[something]
This has a benefit of using a regexp, so you can generalise easier:
validates_format_of :string, :without => /A(something)/
You can extend to other words with /A(something|somethingelse|somemore)/
/A(something|somethingelse|somemore)/
This is the general case with which you can achieve any validation:
validate :cant_be_something def cant_be_something errors.add(:string, "can't be something") if self.string == "something" end
To get exactly the syntax you proposed (validates :string, :not => "something") you can use this code (a warning though, I discovered this while reading the master branch of the rails source and it should work, but it doesn't work on my ~ 3 months old install). Add this somewhere in your path:
validates :string, :not => "something"
class NotValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with] end end
2.1m questions
2.1m answers
60 comments
57.0k users