Sneha Kachroo
Sneha Kachroo

Reputation: 593

Validation for non-negative integers and decimal values

My fields are: tax rate and tax amount in which I want to validate positive values.

I wrote this validation:

:format => { :with => /\A[+]?\d+\Z/}

But it is not taking numbers with a decimal point like 4.67. And it's throwing me an error. What type of validation will work on integers and floating point values? for example: 2, 57, 54.56 should pass but -2.56, -87 should fail.

Upvotes: 52

Views: 46528

Answers (3)

Justin
Justin

Reputation: 53

you could use validates_numericality_of :amount, :greater_than => 0.0

Upvotes: 5

Oswaldo Ferreira
Oswaldo Ferreira

Reputation: 1339

You could use:

validates :tax_rate, inclusion: { in: 0..5 }

It allows values like: 0, 2, 1.2, 3.2

Hope it helps!

Upvotes: 8

dimuch
dimuch

Reputation: 12818

Doesn't this work?

validates :your_field, :numericality => { :greater_than_or_equal_to => 0 }

(guess for taxes following rule will be more correct:)

validates :your_field, :numericality => { :greater_than_or_equal_to => 0, :less_than_or_equal_to => 100 }

Upvotes: 150

Related Questions