Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails : Validates_format_of for float not working

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?

like image 586
Krishna Kumar Avatar asked Nov 15 '11 14:11

Krishna Kumar


People also ask

Is it possible to create your own validations in rails?

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.

What happens when a validation error occurs on a form field?

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.

What happens when an attribute validation fails?

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.

What are the default error messages for the validation helpers?

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.


2 Answers

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

like image 157
peter.cambal Avatar answered Oct 29 '22 11:10

peter.cambal


For rails 3:

validates :price, :format => { :with => /^\d+??(?:\.\d{0,2})?$/ }, 
:numericality =>{:greater_than => 0}
like image 20
Taimoor Changaiz Avatar answered Oct 29 '22 11:10

Taimoor Changaiz