Need <f:convertNumber> to throw error when fractions or separator characters are used

谁都会走 提交于 2019-12-02 12:00:18

问题


I have an InputText component wired to a Bean property of int type. However, I'm forced to use NumberConverter only

Even when I specify integerOnly = true, it accepts doubles by removing the fractional part and no error is thrown in Validation phase

My question is, is there a way for NumberConverter to throw conversion exception and error message (preferably client side, I mean, when I tab out of the field)

We are using JSF 1.2

(Actually, NumberConverter's getAsObject() has this code which should be throwing exception when converting from BigDecimal to Integer when there is a loss of precision

GenericConverterFactory fac = GenericConverterFactory .getCurrentInstance();
      try
      {
        value = fac.convert(value, expectedType);
      }

)

回答1:


Create a custom converter extending the default NumberConverter wherein you check the string value before delegating to the NumberConverter and then use it instead.

public class MyNumberConverter extends NumberConverter {

    public MyNumberConverter() {
        setIntegerOnly(true);
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        if (submittedValue != null && !submittedValue.matches("[0-9]+")) {
            throw new ConverterException("Please enter digits only");
        }

        return super.getAsObject(context, component, submittedValue);
    }

}
<f:converter converterId="myNumberConverter" />


来源:https://stackoverflow.com/questions/14848675/need-fconvertnumber-to-throw-error-when-fractions-or-separator-characters-are

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