1

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>

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;

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" />

When I put an invalid number I get this message from the validator:

form:price: 'ss' is not a number. Example: 99

My custom messages from the properties are not working. What is wrong?

John Alexander Betts
  • 4,718
  • 8
  • 47
  • 72

1 Answers1

5

You're mixing several concepts and it isn't entirely clear what exactly you want, so it's hard to provide the right answer.

First of all, the @Pattern works only on String properties. If you intend to allow [0-9] only, just use Integer or Long instead of Double. If necessary, use a @Min to not go lower than 0. This way you can also get rid of the whole <f:convertNumber>. However, this way you can't validate as number by JSR 303 then. It's thanks to the strong typed nature of Java already impossible to set the property with a syntactically invalid number. The conversion error which you're facing is actually coming from JSF's <f:convertNumber> which is implicitly also already used with default settings when a java.lang.Number property is been used, such as Double, Long and friends.

Your best bet is to specify the conversion error message in JSF side. You can do by either specifying converterMessage attribute of the input field:

<p:inputText ... converterMessage="#{bundle['not.a.valid.number']}" />

Or by overriding the JSF default conversion error message via <message-bundle> with this key:

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

If you really need to be able to validate it by @Pattern of JSR303 bean validation, then declare the property as a String. But this completely defeats the strong typed nature of Java.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I use Double value because the field in DB is stored as double. Is there a better way to validate Doubles or Integers? For example with omnifaces? – John Alexander Betts Sep 23 '13 at 20:37
  • 1
    Your best bet is a custom JSF converter. You can validate the pattern on a string value before parsing and returning as double. OmniFaces offers no builtin facilities for this. – BalusC Sep 24 '13 at 13:10
  • I've answered a similar question before: http://stackoverflow.com/questions/14848675/need-fconvertnumber-to-throw-error/ – BalusC Sep 24 '13 at 13:11