4

Job model has an integer job_price field:

class CreateJobs < ActiveRecord::Migration
  def self.up
    create_table :jobs do |t|
      ...
      t.integer "job_price"
      ...
    end
  end
  ...
end

I would like to display an error message if user types strings in the job_price field, so I added the following validation:

class Job < ActiveRecord::Base 
  validates_format_of :job_price, :with => /\A\d{0,10}\z/, 
                      :message => "^Job Price must be valid"
  ...
end

However, it seems like the validation passes even when I type strings.

Any ideas why ?


Note

I had to add :value => @job.job_price_before_type_cast here:

f.text_field(:job_price, :maxlength => 10, 
             :value => @job.job_price_before_type_cast)

because, otherwise, if I was typing abc5, for example, and then submit the form, Rails was converted it to 5 (I guess because job_price is defined as integer).

3 Answers 3

6

You could ensure it's an integer and in a range:

validates_numericality_of :myfield, :only_integer => true
validates_inclusion_of :myfield, :in => 0..9999999999
Sign up to request clarification or add additional context in comments.

1 Comment

I'm finding that numeric values given for integer-type attributes seem to have already been rounded to integers prior to validation, so fractional entries are treated as valid, even when the :only_integer => true option is used.
3

Rails 3 way would be:

validates :myfield, :numericality => { only_integer: true }
validates :myfield, :inclusion => { :in => 1..10000 }

Comments

2

ActiveModel does have a built-in validation method for integers.

validates_numericality_of

Hopefully will behave how you want it to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.