Skip to content

Customising number fields

Miki edited this page Jun 1, 2023 · 1 revision

Number fields are quite flexible and allow customising most of their functionality. Many of the features are self-explanatory, for example:

  • locale
  • number of digits
  • allowing negative values or null value
  • integer part being optional
  • autoselect on focus
  • selection events

Custom separators and negative sign

Since version 0.18.2 it is possible to allow alternative grouping separators, decimal separators and negative signs. Those symbols are taken from the current locale of the component, but adding alternatives is possible through dedicated methods (setXYZAlternatives or withXYZAlternatives).

Alternative symbols are something that can be typed in by the user, but as soon as the number field loses focus, the value is formatted according to the locale-defined format, using symbols defined in that locale. As an example, you may allow _ to be used as a grouping separator in addition to , used by the locale. A user can type 1_000_000 as a valid input, and it will be replaced with 1,000,000 that represents an integer 1000000.

By default, those alternatives may not override any of the existing symbols - so if the locale uses . as a decimal separator, setting . as a grouping separator or a negative sign alternative will have no effect. Of course, this can be changed by allowing the alternatives to overlap (.setOverlappingAlternatives(true) or .withOverlappingAlternatives()). In such case the symbols may overlap and will be processed in a fixed order:

  • any of the negative sign alternatives will be replaced with a negative sign valid for the locale;
  • followed by any of grouping (thousand) separator alternatives being replaced with a locale-defined symbol;
  • followed by any of decimal separator alternatives being replaced with a locale-specific symbol.

Note that some locales use [NBSP] (the non-breaking space) as a grouping separator. When that happens, regular is always added as an alternative (and removed when the locale changes, unless it has been added manually).

Preventing alternative symbols from being typed

Note: this feature is not available in versions for Vaadin 14 because text fields behave a bit differently.

Also note: this feature is considered experimental and may change in future releases.

It is possible to disallow typing certain alternative characters (but still allow them via e.g. pasting text). To use that simply call .setKeyboardDisallowedAlternatives(...) with those characters. Note that it is not possible to prevent entering locale's default symbols.