rails 3 validation of a string

后端 未结 2 645
余生分开走
余生分开走 2020-12-15 09:06

hiho

Is there any way to tell rails that my string may not be \'something\'?

I am searching for something like

validates :string, :not =>          


        
2条回答
  •  旧时难觅i
    2020-12-15 10:06

    A couple of ways. If you have exact list of what it can't be:

    validates_exclusion_of :string, :in => ["something", "something else"]
    

    If you want to ensure that it doesn't exist as a substring at all:

    validates_format_of :string, :with => /\A(?!something)\Z/
    

    If it is more complicated and you want to hide the messy details:

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

提交回复
热议问题