开发者

rails 3 validation of a string

开发者 https://www.devze.com 2023-02-09 01:07 出处:网络
hiho Is there any way to tell rails that my string may not be \'something\'? I am searching for something like

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):

  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
    


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号