Reputation: 1340
I have trouble getting custom error messages to work with Spring 3.2. Here is my configs:
Config:
@Configuration
@EnableWebMvc
@EnableJpaRepositories(basePackages = {"com.."})
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.."})
public class Config extends WebMvcConfigurerAdapter {
@Bean
public PersistenceExceptionTranslator jpaExceptionTranslator() {
return new HibernateExceptionTranslator();
}
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(
DataSource ds, JpaVendorAdapter jva) {
LocalContainerEntityManagerFactoryBean factoryBean =
new LocalContainerEntityManagerFactoryBean();
factoryBean.setPackagesToScan(new String[] { "com.." });
factoryBean.setDataSource(ds);
factoryBean.setJpaVendorAdapter(jva);
factoryBean.afterPropertiesSet();
return factoryBean;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
converters.add(converter);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
And here's messages_en_US.properties file:
Pattern.userdto.email=Invalid email.
Pattern=Invalid syntax.
UserDTO class:
public final class UserDTO {
@Size(min = MIN_EMAIL_LENGTH, max = MAX_EMAIL_LENGTH)
@Pattern(regexp = EMAIL_PATTERN)
private String email;
...
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
...
}
Validation is triggered using javax.validation.Valid annotation.
I'm expecting that this would print out "Invalid email" when the given email doesn't match the pattern, but I'm getting "Invalid syntax" message.
Upvotes: 1
Views: 2773
Reputation: 1340
It started working after changing message key to:
Pattern.userDTO.email
Upvotes: 1
Reputation: 18990
You need to specify the key of the message to be used within the @Pattern
constraint:
...
@Pattern(regexp = EMAIL_PATTERN, message = "Pattern.userdto.email")
private String email;
...
Otherwise the default key is used (which is "{javax.validation.constraints.Pattern.message}").
Upvotes: 1