【问题标题】:rails 3 validation of a stringrails 3验证字符串
【发布时间】:2011-02-08 13:08:58
【问题描述】:

有什么方法可以告诉 Rails 我的字符串可能不是“某物”?

我正在寻找类似的东西

validates :string, :not => 'something'

谢谢 团团

【问题讨论】:

    标签: ruby-on-rails validation ruby-on-rails-3


    【解决方案1】:

    其中任何一个都可以完成工作(单击文档方法):

    1. 可能是最好最快的方式,换句话来说很容易扩展:

      @987654321@ :string, :in => %w[something]
      
    2. 这有一个使用正则表达式的好处,所以你可以更容易地概括:

      @987654322@ :string, :without => /\A(something)\Z/
      

      您可以使用/\A(something|somethingelse|somemore)\Z/ 扩展到其他单词

    3. 这是实现任何验证的一般情况:

      @987654323@ :cant_be_something
      def cant_be_something
        @987654324@(:string, "can't be something") if self.string == "something"
      end
      
    4. 要准确获得您建议的语法 (validates :string, :not => "something"),您可以使用此代码(不过是一个警告,我在阅读 rails 源代码的 master 分支时发现了这一点,它应该可以工作,但它没有在我的〜 3 个月大的安装上工作)。在你的路径中添加这个:

      class NotValidator < @987654325@
        def @987654326@(record, attribute, value)
          record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
        end
      end
      

    【讨论】:

    • 是的,我想我们都非常详尽地介绍了它;) 使用 \A\Z 可能是一个更安全的想法 - 很好。
    【解决方案2】:

    有几种方法。如果你有它不可能的确切清单:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-04-14
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      相关资源
      最近更新 更多