验证某个值是否在某个范围内,例如1

时间:2022-03-30 16:40:53

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

我想验证一个数字:值在1或2之内

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

However, the above code is failing the validation when value == 1

但是,当值== 1时,上述代码未通过验证

Please ensure that your solution allows me to add a message for the validation.

请确保您的解决方案允许我添加验证消息。

3 个解决方案

#1


33  

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

See http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

请参阅http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

#2


16  

You're looking for validates_inclusion_of:

您正在寻找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:

您还可以使用(相当新的)shothand表单和Range而不是Array:

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

#3


13  

if you want it to be a number within 1 and 2 ( 1.5, 1.6839749, etc ) do

如果你想让它成为1和2之内的数字(1.5,1.6839749等)呢

validates_numericality_of :value, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 2, :message => "blah"

may not be what you are looking for but is worth noting,

可能不是你想要的,但值得注意的是,

#1


33  

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

See http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

请参阅http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

#2


16  

You're looking for validates_inclusion_of:

您正在寻找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:

您还可以使用(相当新的)shothand表单和Range而不是Array:

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

#3


13  

if you want it to be a number within 1 and 2 ( 1.5, 1.6839749, etc ) do

如果你想让它成为1和2之内的数字(1.5,1.6839749等)呢

validates_numericality_of :value, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 2, :message => "blah"

may not be what you are looking for but is worth noting,

可能不是你想要的,但值得注意的是,