Spring MVC - mapping a single error to multiple fields

In my bean I have a list

List<SomeClass> values = new ArrayList<SomeClass>(); SomeClass{ int a; int b; int c; } 

My verification code is

 int i =0 for(SomeClass entry: values){ if(entry.getA() < 0 && entry.getB() < 0 && entry.getC() > 0){ bindingResult.addError(newFieldError("bean", "values[" + i"].a", values.get(i).getA(),false,new String []{"error.code"}, null, null)); } } 

error.code maps to String " If C is greater than zero, then A and B must be greater than zero "

The problem is that I want to map the error code to values[i].a , as well as values[i].b , so that these two fields are highlighted in the user interface.

The FieldError constructor accepts a String field , not a String [] fields .

Is it possible to add two error fields for the same error?

thanks

+4
source share
1 answer

Once you find the condition for which you want to display a validation message with several fields highlighted, you can use the code below to display a generic / global error message:

 if ("your error condition"){ errors.rejectValue("your.error.code"); } 

Then update the model with Boolean flags corresponding to the fields that should be highlighted.

 model.addAttribute("xFieldHighlighted", true); model.addAttribute("yFieldHighlighted", true); 

Then use JavaScript to highlight the fields. JQuery example below:

 var xFieldHighlighted = '${xFieldHighlighted}'; var yFieldHighlighted = '${yFieldHighlighted}'; if (xFieldHighlighted == 'true'){ $('#xFieldID').addClass('cssError'); } if (yFieldHighlighted == 'true'){ $('#yFieldID').addClass('cssError'); } 
0
source

Source: https://habr.com/ru/post/1497724/


All Articles