Rails 3: Why is the whole field not checked for regular expression?

Job job_price model has an integer job_price :

 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 the user enters lines in the job_price field, so I added the following check:

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

However, the check seems to be performed even when entering lines.

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 typed abc5 , for example, and then submitted the form, Rails converted it to 5 (I think because job_price is defined as an integer).

+4
source share
3 answers

You can provide an integer in the range:

 validates_numericality_of :myfield, :only_integer => true validates_inclusion_of :myfield, :in => 0..9999999999 
+6
source

Rails 3 ways:

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

ActiveModel has a built-in method for checking integers.

validates_numericality_of

I hope you will behave the way you want.

+2
source

Source: https://habr.com/ru/post/1343272/


All Articles