Rails 3 字符串验证

14

有没有办法告诉 Rails,我的字符串可能不是某个特定的值?

我正在寻找类似下面的方法:

validates :string, :not => 'something'

谢谢 klump

2个回答

23

以下两种方法都可以完成任务(点击链接查看详细文档):

  1. Probably the best and fastest way, easy to extend for other words:

    <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_exclusion_of">validates_exclusion_of</a> :string, :in => %w[something]
    
  2. This has a benefit of using a regexp, so you can generalise easier:

    <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_format_of">validates_format_of</a> :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:

    <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validate">validate</a> :cant_be_something
    def cant_be_something
      <a rel="noreferrer" href="http://apidock.com/rails/v3.0.0/ActiveModel/Errors/add">errors.add</a>(: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 < <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/EachValidator">ActiveModel::EachValidator</a>
      def <a rel="noreferrer" href="http://apidock.com/rails/ActiveModel/EachValidator/validate_each">validate_each</a>(record, attribute, value)
        record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
      end
    end
    


是的,我想我们都已经详尽地讨论了它 ;) 使用\A\Z可能是一个更安全的想法 - 很好的发现。 - Jakub Hampl

7
有几种方法。如果您有不能使用的确切列表:
validates_exclusion_of :string, :in => ["something", "something else"]

如果你想确保它不作为子字符串存在:
validates_format_of :string, :with => /\A(?!something)\Z/

如果情况更加复杂,您想要隐藏混乱的细节:
validate :not_something

def not_something
  errors.add(:string, "Can't be something") if string =~ /something/
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接