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)
来自属性的我的自定义消息不起作用.怎么了?
你混合了几个概念,并不完全清楚你想要什么,所以很难提供正确的答案.
首先,@Pattern
仅适用于String
属性.如果您打算[0-9]
只允许,只需使用Integer
或Long
代替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}
如果您确实需要通过@Pattern
JSR303 bean验证来验证它,那么将该属性声明为String
.但这完全打败了Java的强大类型.
归档时间: |
|
查看次数: |
1438 次 |
最近记录: |