Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

validation - How to implement min/max validator in Rails 3?

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

I have a model, with min_age and max_age attributes.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

spec:

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}")
}

code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...