我想强制用户输入小数点后正好2位数的数字。 目前,当用户键入12.349时,它将自动转换为12.35。相反,应该提出验证错误,如:"请输入小数点后2位数字。"
class Accounting < ActiveRecord::Base
validates :share_ksk, :central_office, :limit_value, :fix_disagio,
presence: true, numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 }
end
我的迁移文件:
class CreateAccountings < ActiveRecord::Migration
def change
create_table :accountings do |t|
t.decimal :share_ksk, precision: 5, scale: 2, null: false
t.decimal :central_office, precision: 5, scale: 2, null: false
t.decimal :limit_value, precision: 5, scale: 2, null: false
t.decimal :fix_disagio, precision: 5, scale: 2, null: false
t.timestamps null: false
end
end
end
答案 0 :(得分:1)
您可以使用format
验证执行此操作,并为其指定正则表达式:
validates :share_ksk, :central_office, :limit_value, :fix_disagio,
presence: true,
numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 },
format: { with: /\d*\.\d{2}$/, message: "must have two digits after decimal point" }
请参阅:http://guides.rubyonrails.org/active_record_validations.html#format