How to create a custom formatter (number masking) for an input field?

I would like to create a custom formatter for an input field to format numbers in a prescribed way (say different thousand separators, decimal points, etc.). Is there a good way to go about this without a custom component?

Transformer could be a way, but the app is blocking it for a dependency cycle, which could be avoided if I return only when I want to change the value, but seems like it's not intended to work as such.

I did find another way, but I question the performance of that. I created a JS query and found a hacky way to define a watched input (not sure if it's bugged or the way it's supposed to work – there's no docs about it in any case).

  • Add {{textinput1.value}} under "Disable query"
  • Add {{!textinput1.value}} under "Watched inputs"
  • Remove {{!textinput1.value}} from "Disabled query" or replace with {{!textinput1.value}}
  • Add the following code:
const initialValue = textinput1.value;
let value = initialValue.replace(/[^\d.-]/g,'').split('.');
value[0] = value[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
value = value.join('.');

if (value !== initialValue) {
  textinput1.setValue(value); 
}

Are there other, better / less hacky ways to go about it or any downsides to doing it like I did above?

Hey Lauri,

We’ve discussed more robust native formatting features for inputs—that’s ultimately probably the best solution here. Out of curiosity, are you trying to validate the data as well, or just assuming that the input is correct?

In the near term, a replace via regex like what you posted is how I’d probably approach it. Not ideal, but gets the job done.

1 Like

I’m mainly concerned in the visual representation of the number, so formatting/updating while typing rather than applying formatting post-factum. Users will enter numbers in millions, so comma separation matters to visually make sure that the entered number is correct. But sometimes also smaller numbers with many decimal points.

That makes sense, thanks for the color. I will pass along this feedback to the team!