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