how to return a custom message in jsp using spring 3 mvc and hibernate validator(jsr303)
I have a project using spring 3 mvc and hibernate validator to validate form object.
I follow spring's document
In my controller, I can get bindingresult, which bindingresult.hasErrors() == true
.
I use ReloadableResourceBundleMessageSource
to do the error message binding.
For example, I want to say "the app name UserEnteredAppName is not valid. The size should be between 2 and 255".
In my message.property, I define:
Size.appNameForm.itemName=the app name {What Should I do in this brace?} is not valid. The size should be between {1} and {2}
{1} and {2} can be interpolated to '2' and '255'. but how can I get the UserEnteredAppName in the interpolated message?
Below is my form class and controller class:
My controller class:
@RequestMapping(value="foo.htm")
public String handleAppNameFormSubmit(@Valid @ModelAttribute("appNameForm") AppNameForm form, BindingResult result){
}
My form class:
public class AppNameForm implements IForm{
@NotEmpty
@Size(min = 1, max = 255)
private String itemName;
....
}
I find some l开发者_开发知识库inks which give me some hint:
for example: How do I dynamically resolve message parameters with Hibernate Validator?
But I am using spring mvc and spring controll which jsr303 implementation to use, I cant find a way to use custom validator, extending hibernate's default ValidatorImpl.
What I am thinking the solution is, I can have custom validator, which will reject the UserEnteredAppName into the bindingResult. is it possible? or I should find another way?
Thanks Andrew
As of release 4.2 Hibernate Validator provides ValueFormatterMessageInterpolator, a new message interpolator which should fulfill your requirements.
With that interpolator you can refer to the validated value using the place holder ${validatedValue}
. You can also specify a format string to be applied like this: ${validatedValue:[format string]}
, e.g. ${validatedValue:%1$ty}
if the validated value is a date.
An example for using this interpolator can be found in the Hibernate Validator reference guide.
精彩评论