Mahmoud Saleh
Mahmoud Saleh

Reputation: 33625

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.

Upvotes: 7

Views: 1948

Answers (1)

Victor Martinez
Victor Martinez

Reputation: 1112

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:

Upvotes: 5

Related Questions