Custom message from @Pattern not shown on a Double property

Joh*_*tts 1 jsf bean-validation

I am trying to use JSR-303 bean validation.

I added the maven dependency

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

I put ValidationMessages_es.properties and ValidationMessages_en.properties in /WEB-INF/classes.

This is the model:

@Pattern(regexp="[0-9]", message="{not.a.valid.number}")
private Double price;
Run Code Online (Sandbox Code Playgroud)

And this is the view:

<p:inputText id="price"
    value="#{inventoryMB.product.price}">
    <f:convertNumber type="number" maxFractionDigits="0" />
</p:inputText>
<p:message for="price" />
Run Code Online (Sandbox Code Playgroud)

当我输入无效数字时,我从验证器收到此消息:

form:price: 'ss' is not a number. Example: 99
Run Code Online (Sandbox Code Playgroud)

来自属性的我的自定义消息不起作用.怎么了?

Bal*_*usC 5

你混合了几个概念,并不完全清楚你想要什么,所以很难提供正确的答案.

首先,@Pattern仅适用于String属性.如果您打算[0-9]只允许,只需使用IntegerLong代替Double.如有必要,使用a @Min不要低于0.这样你也可以摆脱整体<f:convertNumber>.但是,这样您就无法通过JSR 303验证为数字.这要归功于Java强大的类型特性已经无法使用语法上无效的数字设置属性.你面临的转换错误实际上是从JSF的未来<f:convertNumber>,当一个被隐含也已经使用默认设置java.lang.Number是使用了财产,比如Double,Long和朋友.

最好的办法是在JSF端指定转换错误消息.您可以通过指定converterMessage输入字段的属性来执行:

<p:inputText ... converterMessage="#{bundle['not.a.valid.number']}" />
Run Code Online (Sandbox Code Playgroud)

或者通过<message-bundle>使用此键覆盖JSF默认转换错误消息:

javax.faces.converter.NumberConverter.NUMBER_detail={2}: ''{0}'' is not a number. Example: {1}

如果您确实需要通过@PatternJSR303 bean验证来验证它,那么将该属性声明为String.但这完全打败了Java的强大类型.