7

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.

Mahmoud Saleh
  • 33,303
  • 119
  • 337
  • 498
  • it's wierd, i don't know why, but when i used @Size and give it max,everything works as expected, any ideas ? – Mahmoud Saleh Sep 26 '11 at 14:01
  • 1
    `@Size` and `@Max` are not the same. The `@Size` validates the length of the string input value. `@Max` validates the numerical value of any number input value. E.g. 26 would not pass on `@Max(25)`. – BalusC Sep 26 '11 at 17:25

1 Answers1

5

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:

Community
  • 1
  • 1
Victor Martinez
  • 1,102
  • 2
  • 8
  • 22
  • Nice catch! In that case the OP can also just use `@NotNull` instead of the hibernate-impl-specific `@NotBlank`. – BalusC Sep 26 '11 at 17:24