What is the best way to validate a cost/price input by a user, validation rules below:
#rails 3
validates :price, :format => { :with => /\A\d+(?:\.\d{0,2})?\z/ }, :numericality => {:greater_than => 0, :less_than => 10}
#rails 2
validates_numericality_of :price, :greater_than => 0, :less_than => 10
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/
For client side validations you can use a jQuery plugin like this one that allows you to define different valid formats for a given input.
For server side validations and according to this question/answer maybe you should use a decimal
column for price
in which you can define values for precision
and scale
, scale
solves the two digits after decimal point restriction.
Then to validate the numericality, minimum and maximum value you can use the next validation method:
validates_numericality_of :price, :greater_than => 0, :less_than => 10
You can build custom validations.Lets say, for example the second case:
validate :price_has_to_be_greater_than_minimum
def price_has_to_be_greater_than_minimum
errors.add(:price, "price has to be greater than 0.01") if
!price.blank? and price > 0.01
end
More on this, in the Rails Guides, here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.