开发者

How do you order the display of BindingResult errors according to the order of the fields on the page?

开发者 https://www.devze.com 2023-03-20 22:34 出处:网络
I am using the hibernate implementation of jsr303 for server side validation.When Set<ConstraintViolation<?>> is returned I immediately add th开发者_JAVA技巧e errors to a BindingResult for

I am using the hibernate implementation of jsr303 for server side validation. When Set<ConstraintViolation<?>> is returned I immediately add th开发者_JAVA技巧e errors to a BindingResult for display on the page. I display the errors with a form:errors tag all in one location. The errors display on the page in any random order. Is there any way to coax Spring into displaying the errors according to the order of the fields on the page?


You can sort the field errors using a custom Comparator:

private static final Comparator<FieldError> FIELD_ORDER_COMPARATOR = new Comparator<FieldError>() {

    // Your fields, ordered in the way they appear in the form
    private static final List<String> FIELDS_WITH_ORDER = ImmutableList.of("field1", "field2");

    @Override
    public int compare(FieldError fe1, FieldError fe2) {

        String field1 = fe1.getField();
        String field2 = fe2.getField();

        int field1Index = FIELDS_WITH_ORDER.indexOf(field1);
        int field2Index = FIELDS_WITH_ORDER.indexOf(field2);

        return NumberUtils.compare(field1Index, field2Index);
    }
});

...

List<FieldError> fieldErrors = bindingResult.getFieldErrors();
Collections.sort(fieldErrors, FIELD_ORDER_COMPARATOR);
0

精彩评论

暂无评论...
验证码 换一张
取 消