rails 3validation字符串
嗨
有没有办法告诉我,我的字符串可能不是’某事’?
我正在寻找类似的东西
validates :string, :not => 'something'
谢谢klump
这些中的任何一个都可以完成这项工作(单击文档的方法):
-
可能是最好和最快的方式,易于扩展为其他词:
validates_exclusion_of :string, :in => %w[something]
-
这有使用正则表达式的好处,因此您可以更容易地概括:
validates_format_of :string, :without => /\A(something)\Z/
您可以使用
/\A(something|somethingelse|somemore)\Z/
扩展到其他单词/\A(something|somethingelse|somemore)\Z/
-
这是您可以进行任何validation的一般情况:
validate :cant_be_something def cant_be_something errors.add (:string, "can't be something") if self.string == "something" end
-
为了获得你提出的语法(
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
有两种方法。 如果你有一个不可能的确切列表:
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