在使用JSR-303验证表单时使用I18n消息 [英] Using I18n messages while validating forms with JSR-303

查看:176
本文介绍了在使用JSR-303验证表单时使用I18n消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用是带有百里香模板引擎的完全配置的spring-boot应用. I18n也进行了配置,因此我可以在模板中使用它.这是我使用的配置:

My app is fully-configured spring-boot app with thymeleaf templates engine. I18n configured as well so I can use it within my templates. Here is the config I use:

spring.messages.basename=i18n/messages

虽然手动验证字段I18n也可以正常工作

While manual validating fields I18n also work fine:

BindingResult result;
result.rejectValue("field", "some.i18n.code");

但是一旦我想实现一些自定义的ConstraintValidator对象并使用message字段-不涉及I18n,我将收到纯代码作为响应而不是消息. IE.

But once I want to implement some custom ConstraintValidator objects and use message field - no I18n involved, I receive plain codes as a response instead of a message. I.e.

{some.i18n.code}

我尝试了此解决方案-没有结果. -结果相同.

I tried this solution - no result. This on as well - same result.

我想念什么?

推荐答案

我想我找到了解决方案,也许对其他人会有帮助.您要做的就是将以下定义添加到您的WebMvcConfigurerAdapter配置实现中:

I guess I found the solution, maybe it will be helpful to others. All you have to do is to add the following definitions into your WebMvcConfigurerAdapter configuration implementation:

@Autowired
private MessageSource messageSource;

@Bean
public LocalValidatorFactoryBean validator() {
     LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
     validatorFactoryBean.setValidationMessageSource(messageSource);

     return validatorFactoryBean;
}

@Override
public Validator getValidator() {
     return validator();
}

这篇关于在使用JSR-303验证表单时使用I18n消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆