Need to specify max length for numeric filed type in simple_form

1.5k Views Asked by At

I need to restrict the user from entering the only integer for one of my column with length specification.

<%= f.input :value, as: :numeric, :input_html => { :maxlength => 4 } %>

The above works for string type of field in the UI, but when I add numeric to restrict alphanumeric input, then the max length is not working.

the expectation is to limit the input to 4 char maximum, and it should be positive number input only

1

There are 1 best solutions below

3
On

If your "value" attribute is an integer you don't need to specify the "as" in simpleform as it will automagically handle that for you:

<%= f.input :value, as: :integer, input_html: { min: '0', max: '9999', step: '1' } %> 
#If you want decimals you can change :step to 'any'

My personal preference is to use jquery-mask: https://igorescobar.github.io/jQuery-Mask-Plugin/docs.html

In your view you then apply it like (assuming turbolinks wasn't disabled):

$( document ).on('turbolinks:load', function() {
  $('#input-id-here').mask('0000');
})