5

I am using <f:convertNumber> tag to convert a decimal input.

<f:convertNumber minFractionDigits="2" />

But it's accepting trailing alphabatic characters. For example, if I input 12345.1234AAA it converts to 12345.123. I would like it to throw a conversion error on that instead of trimming the alphabetic characters. How can I achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Tripp
  • 45
  • 7

1 Answers1

3

This simply is the standard behavior of java.text.NumberFormat as used by <f:convertNumber>: It trims all entries after the first not-allowed character (e.g. letters or decimal separators others than the ones defined in the input locale). Conversion only fails if the offending character is at the beginning.

I don't really like this behaviour because a user may not notice his mis-typed value got trimmed, resulting in unintended and (even worse) unnoticed auto-correction into a wrong value.

Interestingly enough, the specific number converters behave differently. Using <f:converter converterId="javax.faces.Double" /> does not automatically handle non-numerical input, but fails conversion instead. However, the tag does not possess the additional attributes of convertNumber, such as minFractionDigits or currency symbols.

A different approach would be to write your own custom converter which extends the standard converter as described in this answer. You could then check the value for characters and directly abort further processing (throwing an according conversion exception) if you find any. If the value is already character-free you could call the standard behavior of the converter you derive from.

The drawback of both ways is that you loose the additional capabilities of convertNumber. You do not have attributes such as minFractionDigits or currencySymbol on <f:converter>, so if you need this you'd have to find another way to pass in a parameter. Our implementation does not require any of these, so I haven't looked into this any further (we went for approach A), but this answer presents an approach to do so.

Community
  • 1
  • 1
Louise
  • 1,451
  • 1
  • 18
  • 40