Search code examples
jsfjsf-2bean-validationhibernate-validator

Multiple validators on one field with JSF bean validation


i am trying to make multiple validation one one field

    @NotBlank(message = "{name.required}")
    @Max(value = 25, message = "{long.value}")
    public String name;

JSF:

<h:inputText id="name" value="#{person.name}" size="20">
</h:inputText>
<h:message for="name" style="color:red" />

but when i leave the field empty, it shows both error messages.

any ideas how to handle both cases, validate the empty, and maximum length independently.


Solution

  • If your JSF 2 configuration interpret empty submitted values as "" and not null then :

    The @NotBlank validator returns false because your annotated string is empty.

    The @Max validator returns false because according to hibernate implementation (I guess you are using hibernate implementation base on your previous posts).

    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
            //null values are valid
            if ( value == null ) {
                return true;
            }
            try {
                return new BigDecimal( value ).compareTo( BigDecimal.valueOf( maxValue ) ) != 1;
            }
            catch ( NumberFormatException nfe ) {
                return false;
            }
        }
    

    In your case the value String parameter contains an empty value ("") and the BigDecimal(String) constructor throws an exception and then the validator returns false.

    You have two possible solutions: