rails 3验证字符串

klu*_*ump 12 validation ruby-on-rails ruby-on-rails-3

有没有办法告诉我,我的字符串可能不是'某事'?

我正在寻找类似的东西

validates :string, :not => 'something'
Run Code Online (Sandbox Code Playgroud)

谢谢klump

Jak*_*mpl 21

这些都可以完成任务(单击文档的方法):

  1. 可能是最好和最快的方式,很容易扩展为其他词:

    validates_exclusion_of :string, :in => %w[something]
    
    Run Code Online (Sandbox Code Playgroud)
  2. 这有使用正则表达式的好处,因此您可以更容易地概括:

    validates_format_of :string, :without => /\A(something)\Z/
    
    Run Code Online (Sandbox Code Playgroud)

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

  3. 这是您可以进行任何验证的一般情况:

    validate :cant_be_something
    def cant_be_something
      errors.add(:string, "can't be something") if self.string == "something"
    end
    
    Run Code Online (Sandbox Code Playgroud)
  4. 为了得到你提出的语法(validates :string, :not => "something")你可以使用这个代码(虽然这是一个警告,我在读取rails源的主分支时发现了它,它应该可以工作,但它在我3个月左右的安装中不起作用) .在路径中的某处添加:

    class NotValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
      end
    end
    
    Run Code Online (Sandbox Code Playgroud)


Mar*_*mas 7

有两种方法.如果你有一个不可能的确切列表:

validates_exclusion_of :string, :in => ["something", "something else"]
Run Code Online (Sandbox Code Playgroud)

如果你想确保它根本不存在作为子串:

validates_format_of :string, :with => /\A(?!something)\Z/
Run Code Online (Sandbox Code Playgroud)

如果它更复杂,你想隐藏凌乱的细节:

validate :not_something

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