rails 3 validation of a string

后端 未结 2 638
余生分开走
余生分开走 2020-12-15 09:06

hiho

Is there any way to tell rails that my string may not be \'something\'?

I am searching for something like

validates :string, :not =>          


        
相关标签:
2条回答
  • 2020-12-15 09:51

    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
      

    0 讨论(0)
  • 2020-12-15 10:06

    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
    
    0 讨论(0)
提交回复
热议问题