Hello all, I am wanting to validate that an input is a positive number. I can see where I validate whether it is a number using: validates_numericality_of :myfield But I can''t figure out how to check also that it is greater than 0. Hints anyone? Thanks, Steve
The rails beta book has a great example of dealing with this. Basically
you just need to make a protected method named validate inside of your
model.
class mymodel
protected
def validate
errors.add(:myfield, "myfield is negative") unless myfield >
0.0
end
end
Rails flaunts its awesomeness by automatically calling the validate
method for you before saving.
-Matt Margolis
Steve Odom wrote:
>Hello all,
>
>I am wanting to validate that an input is a positive number. I can see
>where I validate whether it is a number using:
>
>validates_numericality_of :myfield
>
>But I can''t figure out how to check also that it is greater than 0.
>
>Hints anyone?
>
>Thanks,
>
>Steve
>_______________________________________________
>Rails mailing list
>Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
>http://lists.rubyonrails.org/mailman/listinfo/rails
>
>
Matthew Margolis wrote:> class mymodel > protected > def validate > errors.add(:myfield, "myfield is negative") unless myfield > 0.0 > end > endAnother option is class MyModel validate do |record| record.errors.add(:myfield, "myfield is negative") unless record.myfield > 0.0 end end IMPOSSIBLE, adj: (1) I wouldn''t like it and when it happens I won''t approve; (2) I can''t be bothered; (3) God can''t be bothered. - The Hipcrime Vocab by Chad C. Mulligan
Thanks guys. It reinforces that I need to get the beta book. Steve On 6/4/05, Nicholas Seckar <nseckar-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> Matthew Margolis wrote: > > > class mymodel > > protected > > def validate > > errors.add(:myfield, "myfield is negative") unless myfield > 0.0 > > end > > end > > > Another option is > > class MyModel > validate do |record| > record.errors.add(:myfield, "myfield is negative") unless > record.myfield > 0.0 > end > end > > > > IMPOSSIBLE, adj: > > (1) I wouldn''t like it and when it happens I won''t approve; > (2) I can''t be bothered; > (3) God can''t be bothered. > - The Hipcrime Vocab by Chad C. Mulligan > _______________________________________________ > Rails mailing list > Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org > http://lists.rubyonrails.org/mailman/listinfo/rails >