rails 3 validation of a string

后端 未结 2 648
余生分开走
余生分开走 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
      

提交回复
热议问题