fabian-hiller / modular-forms

The modular and type-safe form library for SolidJS, Qwik and Preact
https://modularforms.dev
MIT License
1.05k stars 55 forks source link

Dollar Input fixed to 2 decimal points #228

Open robodna opened 4 months ago

robodna commented 4 months ago

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

fabian-hiller commented 4 months ago

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>
robodna commented 4 months ago

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.

fabian-hiller commented 4 months ago

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.