If you ever need to validate currency in your Ruby on Rails app, simply add the following line of code to the model of your choice.
app/models/yourmodel.rb:
validates :price, :presence => true,
:numericality => true,
:format => { :with => /^\d{1,4}(\.\d{0,2})?$/ }
This will allow values of up to $9999.99 with an optional decimal place (if the decimal is present, no more than 2 digits must follow.) Tweak as needed.
Comments
Note: You are not logged in. This means your comment be automatically sent into moderation and you won't receive emails when a user replies. To log in using GitHub, click the button below. This is a one step process.
Your information is kept private. to RichOnRails.com and will never be given away or sold. Take a look at our Privacy Policy for more details.
Comment Anonymously
The regular expression matches this value
It should be changed to /\d{1,4}(.\d{1,2})?$/
For little suggestion, now rails will warn you if you using ^ and $. It will better using:format => { :with => /\A\d{1,4}(.\d{0,2})?\z/ } instead.