0

in my application i need to do a bean validation on a loaded (persistent) form element in a http-get method. To do this, i used the following code:

DataBinder binder = new DataBinder(formObject);
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
SpringValidatorAdapter springValidator = new SpringValidatorAdapter(validator);
binder.setValidator(springValidator);
binder.validate();
// TODO resolve error codes by message source
BindingResult results = binder.getBindingResult();
modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + "model", results);

Now i have the problem that the defaultMessages in the BindingResult errors contains the message keys, not the resolved message (e.g. "{my.message.key}"). If i do a bean validation by the @Valid annotation in my controller methods, the BindingResult contains the resolved messages. Did I miss something in my manual validation? Or is it now necessary to resolve the message key manually with the MessageSource bean?

  • 2
    You haven't integrated your manual solution with the `MessageSource` so no conversion will be done. You will need to configure it wit the validator. But why this manual contraption as you aren't really binding? You can also just inject the `Validator` instead of creating it yourself (and that should have the proper configured `MessageSource`. – M. Deinum Apr 27 '22 at 09:45
  • @M.Deinum Thanks for the fast answer, this works perfectly. I inject my validator to the controller and use it instead of creating a new one. The validator contains the message source already. I need this post validation to display the error messages in the ui to to alert the user to the current invalid situation. – user3808286 Apr 27 '22 at 10:04

0 Answers0