Validate that a value is in a certain range, e.g. 1 <= val <=2

后端 未结 4 580
南笙
南笙 2021-02-12 09:35

I want to validate a number :value to be within 1 or 2

validates :value, :format => { :with => /1|2/, :message => \"Select number..\" }
         


        
4条回答
  •  再見小時候
    2021-02-12 09:59

    You're looking for validates_inclusion_of:

    validates_inclusion_of :value, :in => [1, 2],
      :message => "Select one of %{value}"
    

    You can also use the (fairly new) shothand form and a Range instead of an Array:

    validates :value, :inclusion => { :in => 1..2 }
    

提交回复
热议问题