Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
899 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 Answer

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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...