开发者

validating decimals inputs in JSF

I want to validate an input as an integer. Thus, any value with decimal fractions should be filtered. But I don't know how to achieve that. I have tried many things, but with the code below, if the input is "61.2", the value is converted to 61, just truncating decimal part. But I want to force a validation error. I am sure I can do it without a custom validator. Thanks

<p:inputText size="5" value="#{bean.intValue}"  converter="#{Integer}">
    <f:convertNumber pattern="#0" integerOnly="true" 开发者_运维知识库maxFractionDigits="0"/>
</p:inputText>


That's not possible as validation runs after conversion. You'd basically need to bind it to a String property instead of an Integer one in order to validate the unconverted value. You'd need to convert it afterwards in the property setter or the managed bean action method. So, if you make it a String property, you could use <f:validateRegex> for this.

<h:inputText value="#{bean.input}" validatorMessage="Please enter digits only">
    <f:validateRegex pattern="\d*" />
</h:inputText>

Alternatively, and IMO better than manually converting it in the setter or action method, you could bring in a custom converter which extends the JSF standard IntegerConverter and validate the pattern in there right before conversion takes place.

@FacesConverter("digitsOnly")
public class DigitsOnlyConverter extends IntegerConverter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        if (!value.matches("\\d*")) {
            throw new ConverterException();
        }

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

}

with

<h:inputText value="#{bean.input}" converterMessage="Please enter digits only">
    <f:converter converterId="digitsOnly" />
<h:inputText>


place minFractionDigits = "0" and pattern=" # # #"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜