eav
eav

Reputation: 2171

javax.validation ORDER of failures-entries as result of validate method

I'm using javax.validation for JSR-303 bean validation.

After calling the validate method, I go through the result and do someting in my GUI(for example highlighting the failed fields in my form).

My question here:

MyBean.java

public class MyBean {

    @Size(min = 1, message = "Please insert title")
    private String title;

    @Size(min = 1, message = "Please insert author")
    private String author;

    @Size(min = 1, message = "Please insert publisher")
    private String publisher;

    // ... something
}

My Validation method:

Set<ConstraintViolation<MyBean>> failures = this.validator.validate(bean);

After that, I iterate over my failures object:

for (ConstraintViolation<MyBean> constraintViolation : failures) {
        propertyPath = constraintViolation.getPropertyPath().toString();
        if (propertyPath.equals("title")) {
            Color bg = new Color(242, 242, 251);
            this.txtTitle.setBackground(bg);

        }
        // some else if for other attributes (for example: author)
        // add error to all error messages
        errorMessage += constraintViolation.getMessage();
}

Now my problem is: The order of these objects in the failures set. It is not correct. Is there a solution to get the correct order?

Thanks to all

Upvotes: 3

Views: 1050

Answers (2)

Hardy
Hardy

Reputation: 19129

It is actually allowed for a Bean Validation implementation to evaluate constraints in any order, unless an order is required due to a group sequence. This is the reason why you get a set of _ConstraintViolation_s in the first place.

Upvotes: 0

Mathieu Le Tiec
Mathieu Le Tiec

Reputation: 501

A Set is not guaranted to keep its elements ordered (HashSet don't). Hence you shouldn't rely on this order and you will probably have to test each ConstraintViolation in order to apply the right process to it for example using constraintViolation.getPropertyPath().

But ideally you should not have to know which failure you are processing, you normally only need to know it's a ConstraintViolation and apply a general method to it

Upvotes: 3

Related Questions