验证JSF中的小数输入 [英] validating decimals inputs in JSF
问题描述
我想验证输入为整数.因此,任何具有十进制小数的值都应过滤.但是我不知道该怎么实现.我已经尝试了很多事情,但是使用下面的代码,如果输入为"61.2",则值将转换为61,仅截断小数部分.但是我想强制验证错误.我相信没有自定义验证程序也可以做到.谢谢
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>
推荐答案
这是不可能的,因为转换后会进行验证.基本上,您需要将其绑定到String
属性而不是Integer
属性,以验证未转换的值.之后,您需要在属性设置器或托管bean操作方法中对其进行转换.因此,如果将其设为String
属性,则可以使用 <f:validateRegex>
.
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>
或者,与IMO相比,用setter或action方法手动转换它更好,您可以引入一个自定义转换器,该转换器扩展了JSF标准
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);
}
}
使用
<h:inputText value="#{bean.input}" converterMessage="Please enter digits only">
<f:converter converterId="digitsOnly" />
<h:inputText>
这篇关于验证JSF中的小数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!