2
我有一个金额由用户输入并希望验证它。我已经写了一个JSF验证器,但是在任何情况下都无法正常工作。这是我的情景:
我在不同的语言环境中的用户,因此我需要应付输入的各种方法,并希望允许以下NumberFormat本地化问题
English
1234
1,234
1234.56
1,234.5
German & Spanish
1234
1.234
1234,56
1.234,5
French
1234
1 234
1234,56
1 234,5
我的问题是用法语为2 & 4被视为选项因为解析在空间处停止,因此使用此代码无效。
public void validate(final FacesContext pContext,
final UIComponent pComponent,
final Object pValue) {
boolean isValid = true;
final Locale locale = (Locale)pComponent.getAttributes().get(USERS_LOCALE);
final Currency currency = (Currency)pComponent.getAttributes().get(CURRENCY);
final NumberFormat formatter = NumberFormat.getNumberInstance(locale);
formatter.setGroupingUsed(true);
formatter.setMinimumFractionDigits(currency.getDefaultFractionDigits());
formatter.setMaximumFractionDigits(currency.getDefaultFractionDigits());
final ParsePosition pos = new ParsePosition(0);
final String stringValue = (String)pValue;
if (pos.getIndex() != stringValue.length() || pos.getErrorIndex() != -1) {
isValid = false;
}
...
我也想确保以下被视为无效,但他们都成功地解析(除当然法国)
1,234,9.56(无效分组)
1,234.567(太多小数对于
任何帮助将非常感激
伊恩
谢谢,学到了一些新东西。关于这方面的更多讨论可以在oracle的错误跟踪器中找到:http://bugs.sun.com/view_bug.do?bug_id=4510618 – 2012-03-08 18:23:10
感谢您的回应,第一个工作,虽然而不是硬代码,我用stringValue.replace ('',symbols.getGroupingSeparator()) – bluesky 2012-03-09 10:03:42
任何人都有关于无效分组和小数位的第二部分? (应该可能使这个问题成为一个单独的问题!) – bluesky 2012-03-09 10:06:47