问题
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