f:convertNumber doesn't throw conversion error on trailing alphabetic characters in decimal

人走茶凉 提交于 2019-12-23 10:17:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11253368/fconvertnumber-doesnt-throw-conversion-error-on-trailing-alphabetic-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!