Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - How to remove a `FieldError` from a BindingResult?

Tags:

java

spring

I have a BindingResult result that has a FieldError registered for the field date. How can I remove this error?

Assume the error was added as result.rejectValue("date", "my_code", "my_message") ;

Thanks in advance

like image 728
th3an0maly Avatar asked Sep 20 '12 14:09

th3an0maly


2 Answers

Well, first of all, BindingResult is an interface, not a concrete class, and the interface doesn't specify any way to remove an error.

Depending on which implementation of the interface you are dealing with, there may be a method (beyond what's specified in the BindingResult interface) to do this, but it seems unlikely.

The only thing that I can think of is to create a new BindingResult instance, then loop through the errors and re-create all but the one that you want to ignore in the new one.

like image 124
GreyBeardedGeek Avatar answered Oct 18 '22 04:10

GreyBeardedGeek


Here is an example that implements @GreyBeardedGuy Answer, Suppose you want to remove the error linked to a field called specialField in the class MyModel with a modelAttribute name as myModel from BindingResult result:

List<FieldError> errorsToKeep = result.getFieldErrors().stream()
                .filter(fer -> !fer.getField().equals("specialField "))
                .collect(Collectors.toList());

        result = new BeanPropertyBindingResult(vacancyDTO, "vacancyDTO");

        for (FieldError fieldError : errorsToKeep) {
            result.addError(fieldError);
        }
like image 3
Ammar Akouri Avatar answered Oct 18 '22 04:10

Ammar Akouri