如何在 Rails 3 中实现最小/最大验证器? [英] How to implement min/max validator in Rails 3?

查看:30
本文介绍了如何在 Rails 3 中实现最小/最大验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 3 中实现最小最大验证器的 Rails 方式是什么?

What is the rails way of implementing a min max validator in Rails 3 ?

我有一个模型,具有 min_age 和 max_age 属性.

I have a model, with min_age and max_age attributes.

年龄可以在 0..100 范围内,但我还想验证交叉值,我的意思是 max 大于或等于 min

Age can be in the range of 0..100, but I want also to validate crossing values, I mean that max is greather than or equal to min

{:min_age => 0, :max_age => 0} => true
{:min_age => 0, :max_age => 1} => true
{:min_age => 1, :max_age => 0} => false # max < min
{:min_age => 1, :max_age => 101} => false # out of 0..100 range

推荐答案

查看 ActiveModel::Validations::NumericalityValidator:RailsAPI NumericalityValidator

Check out the ActiveModel::Validations::NumericalityValidator: RailsAPI NumericalityValidator

规格:

it {
  subject.max_age = 10
  subject.min_age = 20
  subject.should be_invalid
  subject.errors[:min_age].should include("must be less than or equal to #{subject.max_age}")
}

代码:

validates :min_age, numericality: { greater_than: 0, less_than_or_equal_to: :max_age }

validates :max_age, numericality: { less_than_or_equal_to: 100 }

我不知道您是否想验证存在与否,但您只需将其添加为验证的另一个键,例如

I don't know if you want to validate presence or not, but you would just add that as another key to your validations, e.g.

validates :max_age, numericality: { less_than_or_equal_to: 100 }, presence: true

这篇关于如何在 Rails 3 中实现最小/最大验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆