Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 validation of a string

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

like image 796
klump Avatar asked Feb 08 '11 13:02

klump


2 Answers

Either of these will do the job (click on the methods for documentation):

  1. Probably the best and fastest way, easy to extend for other words:

    validates_exclusion_of :string, :in => %w[something]
    
  2. This has a benefit of using a regexp, so you can generalise easier:

    validates_format_of :string, :without => /\A(something)\Z/
    

    You can extend to other words with /\A(something|somethingelse|somemore)\Z/

  3. 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
    
  4. 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:

    class NotValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
      end
    end
    
like image 117
Jakub Hampl Avatar answered Oct 15 '22 14:10

Jakub Hampl


A couple of ways. If you have exact list of what it can't be:

validates_exclusion_of :string, :in => ["something", "something else"]

If you want to ensure that it doesn't exist as a substring at all:

validates_format_of :string, :with => /\A(?!something)\Z/

If it is more complicated and you want to hide the messy details:

validate :not_something

def not_something
  errors.add(:string, "Can't be something") if string =~ /something/
end
like image 40
Mark Thomas Avatar answered Oct 15 '22 16:10

Mark Thomas