I am new at Ruby on Rails. I was trying to validate format of one of the attribute to enter only float.
validates :price, :format => { :with => /^[0-9]{1,5}((\.[0-9]{1,5})?)$/, :message => "should be float" }
but when I enter only character in price, it accepts it and show 0.0 value for price. can anybody tell, what is wrong in this or why this happens?
However, due to the rich number of methods Rails gives you to interact with validations in general, you can build your own. In addition, when generating a scaffold, Rails will put some ERB into the _form.html.erb that it generates that displays the full list of errors on that model.
Assuming we have a model that's been saved in an instance variable named @article, it looks like this: Furthermore, if you use the Rails form helpers to generate your forms, when a validation error occurs on a field, it will generate an extra <div> around the entry.
Every time a validation fails, an error is added to the object's errors collection, and this is associated with the attribute being validated. Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
There is a default error message for each one of the validation helpers. These messages are used when the :message option isn't specified. Let's take a look at each one of the available helpers. This method validates that a checkbox on the user interface was checked when a form was submitted.
This is my solution,
validates :price,presence:true, numericality: {only_float: true}
when you fill in for example 7 it automatically transfer the value to 7.0
For rails 3:
validates :price, :format => { :with => /^\d+??(?:\.\d{0,2})?$/ },
:numericality =>{:greater_than => 0}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With