modular-forms icon indicating copy to clipboard operation
modular-forms copied to clipboard

Dollar Input fixed to 2 decimal points

Open robodna opened this issue 1 year ago • 3 comments

How do I create a transform or mask to ensure a dollar amount entered has 2 decimal points? So entering 10.5 would result in 10.50

robodna avatar Jul 18 '24 11:07 robodna

This could work:

<Field
  name="price"
  transform={toCustom(
    (value) => {
      // Just add decimal points
      return Number(input).toFixed(2);
      // Or format to currency string
      return Number(input).toLocaleString('en', { style: "currency", currency: "USD" });
    },
    { on: 'input' }
  )}
>
  {(field, props) => (
    <input
      {...props}
      type="text"
      placeholder="$0.00"
      value={field.value}
    />
  )}
</Field>

fabian-hiller avatar Jul 18 '24 12:07 fabian-hiller

I tried this however the input box allows 123.12334 even if the transformed value is $123.12

Also, the <input is type="number" and not type="text". I was envisioning a type=number input with a 'mask' which only allows the user to enter a valid currency number. The server/backend returns a number for currency ( eg. 10.5 for 10.50 ). I was looking to just add a prefixed '$' to the input and not make it part of the value.

robodna avatar Jul 18 '24 19:07 robodna

Not sure if I am following, but you can add a "$" before the text element, but that has nothing to do with Modular Forms. It's just the visual representation of your form field. Since Modular Forms is headless, there are no limits.

fabian-hiller avatar Jul 18 '24 19:07 fabian-hiller