In Spring, after validation we get a BindingResult
object in the controller
.
Simple enough, if I get validation errors I want to re-display my form with the error message above each afflicted field.
So to check for field errors on field username
of my FormObject
I call:
FieldError usernameFieldError = bindingResult.getFieldError("username");
Great, now I hold a FieldError
object which, assuming I'm using the DefaultMessageCodeResolver
now contains something like 4 possible error codes.
How do I go from FieldError
-> A string that is consumable to the user?
I have a MessageSource
defined in my webapplication context, so I can map a single error code to a message.
But sometimes the default message will be best, and sometimes I expect that two of the error codes might have a relevant message, so we need to choose the best one.
What method do I use to determine the best possible error message to present for a field error?
You can perform validation with Errors/BindingResult object. Add Errors argument to your controller method and customize the error message when errors found. Below is the sample example, errors. hasErrors() returns true when validation is failed.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
To achieve that, we have to create an error controller bean that'll replace the default one. This way the controller can handle calls to the /error path. In the handleError(), we return the custom error page we created earlier. If we trigger a 404 error now, it's our custom page that will be displayed.
You are, as you guessed, making it way harder on yourself than it needs to be. The FieldError
object is itself a MessageSourceResolvable
. You don't need to get the codes off of it then take individual codes manually to your message source and go looking. You can just pass it to your MessageSource
and it will find the most specific one that has a translation defined in your locale. (assuming your code resolver put them on in the right order.)
You really don't even need to do that in most cases though. Putting the Errors
on your backing object and translating them yourself isn't usually needed. The form
namespace in the jsp library provides a tag that looks up error messages for you. All you need to do is put the Errors
in the ModelMap
. See docs:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-errorstag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With