在我看来,我已经为输入字段添加了类似的验证,并且工作良好。还有另外两个float字段是text_fields,当我使用与之前相同的逻辑时,它不起作用。
.control-group
%label.control-label{ for: 'holding[lat]' }= t('Geo_location')
.controls
= f.text_field :lat, input_html: { step: '0.000001', max: 99.999999 }, placeholder: 'Max 99.999999'
%br
= f.text_field :lng, input_html: { step: '0.000001', max: 99.999999, min: -99.999999 }, placeholder: 'Max -99.999999'
是否有其他方法可以做类似的事情?
这是它工作的字段-= f.input:quantity_acres, label: t('Number_of_acres'), input_html: {step: '0.01', max: 999999.99},占位符:' max 999999.99'
只需在模型中添加此验证
validates :lat, :lng, numericality: { greater_than_or_equal_to: -99.999999, less_than_or_equal_to: 99.999999 }
或者如果lat
和lng
有不同的MIN MAX值,你可以添加两个验证
validates :lat, numericality: { greater_than_or_equal_to: MIN_FOR_LAT, less_than_or_equal_to: MAX_FOR_LAT }
validates :lng, numericality: { greater_than_or_equal_to: MIN_FOR_LNG, less_than_or_equal_to: MAX_FOR_LNG }
用你的数字替换MIN_FOR_LAT
,MAX_FOR_LAT
,MIN_FOR_LNG
,MAX_FOR_LNG
当lat
和lng
是字符串时,它也可以完美地工作
对于发送表单之前的验证,您可以根据表单构建器
使用以下示例之一simple_form
= simple_form_for :your_record do |f|
= f.input :lat, as: :integer, input_html: { step: 0.000001, max: 99.999999, min: -99.999999 }
= f.submit
form_for
= form_for :your_record do |f|
= f.number_field :lat, step: 0.000001, max: 99.999999, min: -99.999999
= f.submit
semantic_form
= semantic_form_for :your_record, html: { novalidate: false } do |f|
= f.inputs do
= f.input :lat, as: :number, step: 0.000001, max: 99.999999, min: -99.999999
= f.actions do
= f.action :submit
在Chrome Version 100.0.4896.127 (Official Build) (x86_64)
中测试