I want to create a simple money input with SimpleForm.
The money field should have a minimum value of 0, so that a user cannot enter a value less than 0.
However I don't know how to define min value with simple form.
I wonder if it's possible.
Definitely! The (simplified) HTML for the form you want looks something like this:
<form>
<input type="number" min="0" step="any" name="amount">
</form>
Notice the two really important properties on the input field: min
is set to 0, because you don't allow negative numbers, and step
is set to any
, because you want to allow decimals in. If you only wanted even dollar amounts, you could set step="1"
, for example. Also, if you wanted to set a max value you could with the max
attribute.
Important Note: this only performs validation on the client side. It's possible to override this if you know what you're doing, so make sure you still validate that the input sent with this form is valid on the server.
I'm not a Ruby guy, but reading through the Simple Form docs, I think this should work:
<%= simple_form_for @transaction do |f| %>
<%= f.input :amount, input_html: { min: '0', step: 'any' } %>
<%= f.button :submit %>
<% end %>
Assuming amount is an number type in your model, it will automatically make an input[type=number] for you.