0

Lets say I have a Table with a text field called player that is null ok. So nulls are allowed, but if not null (has a value) the size of the text/string must be between 10 and 100. I have this to start:

@Column(name = "player", nullable = true)
@Size(min = 5, max = 100)
private String player;

But when Set the field to null the JSF page is throwing a validation error.

Is there a way to make the Size validator ignore nulls?

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29

1 Answers1

6

If player string is null then the Size constraint will not throw any exception. It's a best practice not to throw an error when the value is null (except for NotNull constraint or NotEmpty constraint). The fact is the player bean property value is probably an empty string and not a null value, so the constraint throw an exception, because JSF sends an empty string when nothing is typed in the component. In order to JSF sending a null value you have to add some content in web.xml file as said in the Java EE Tutorial:

In order for the Bean Validation model to work as intended, you must set the context parameter javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL to true in the web deployment descriptor file, web.xml:

<context-param>
    <param-name>
        javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
    </param-name>
    <param-value>true</param-value>
</context-param>

If eventually (depending on versions) the parameter doesn't work as expected see this question for troubleshooting.

EDIT:

You could also try not applying the previous parameter and instead using the Pattern constraint with a Regex pattern similar to (^$|^[a-zA-Z]{3,7}$).

Community
  • 1
  • 1
Javier Haro
  • 1,255
  • 9
  • 14
  • 1
    Kudos to you, you nailed it @lametaweb (muchas gracias). The string was not filled and my app was sending an empty string which of course fails the validation. After adding the context-param `javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL` as suggested - it works flawlessly. Cheers. – Mario Peck Sep 05 '15 at 01:56
  • @Mario Peck, please Mark the answer as correct,if it helped you :) – OndroMih Sep 05 '15 at 06:39
  • Hi @Mario Peck if this answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. – Javier Haro Sep 05 '15 at 09:03
  • Hi @Mario Peck you should see a green tick beside my answer, please revise it. Thanks! – Javier Haro Sep 05 '15 at 17:10