Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

  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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...