Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 227
Mahmoud Saleh Avatar asked Sep 26 '11 10:09

Mahmoud Saleh


1 Answers

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:

  • Configure JSF to interpret empty submitted values as null (or)
  • Change your field name type to numerical instead of String.
like image 185
Victor Martinez Avatar answered Oct 10 '22 07:10

Victor Martinez