Home > Back-end >  Rails adding float validation to text_field
Rails adding float validation to text_field

Time:06-09

On my view I have already added similar validation for input fields and works fine. There is two other float fields that are text_fields, when I use the same logic as before it does not work.

  .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'

Is there another way to do something similar?

This is the field it does work for- = f.input :quantity_acres, label: t('Number_of_acres'), input_html: { step: '0.01', max: 999999.99 }, placeholder: 'Max 999999.99'

CodePudding user response:

Just add this validation in your model

validates :lat, :lng, numericality: { greater_than_or_equal_to: -99.999999, less_than_or_equal_to: 99.999999 }

Or if you have different MIN MAX values for lat and lng you can add two validations

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 }

Replace MIN_FOR_LAT, MAX_FOR_LAT, MIN_FOR_LNG, MAX_FOR_LNG with your numbers

It also perfectly works when lat and lng are strings

For validation before sending the form you can use one of these examples depending on your form builder

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

Tested in Chrome Version 100.0.4896.127 (Official Build) (x86_64)

  • Related