Sergey Chepurnov
Sergey Chepurnov

Reputation: 1447

Spring custom validation message

Custom validation messages don't work. I have a domain class:

...
@RooJpaActiveRecord
public class Letter {

@NotNull(message="{validation.number_empty}")
@Size(min=1,max=20, message="{validation.number_size}")
@Column(length=20, nullable=false)
private String number;
...
}

/WEB-INF/i18n/messages.properties:

 #validation
 validation.number_size=number must be more than 1 and less than 20 symbols
 ...

I want to validate some fields from that domain class during form submitting. Validation works, but I get the output message:

{validation.number_size}

Instead of expected string: number must be more than 1 and less than 20 symbols In other places of my project I use messages from properties files with success.

/WEB-INF/spring/webmvc-config.xml

 <bean     
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource" 
    id="messageSource" 
    p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application" 
    p:fallbackToSystemLocale="false">
 </bean>

Also, I’ve tried , but without success:

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="locations">
       <list>
         <value>classpath:WEB-INF/i18n/messages</value>
       </list>
     </property>
     <property name="ignoreUnresolvablePlaceholders" value="true"/>
     <property name="ignoreResourceNotFound" value="true"/>
 </bean>

Upvotes: 2

Views: 9024

Answers (1)

Shinichi Kai
Shinichi Kai

Reputation: 4523

You need some additional config to customize the error messages using your messageSource.

Try following:

/WEB-INF/spring/webmvc-config.xml:

...

<bean id="validator"
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
  <property name="validationMessageSource" ref="messageSource" />
</bean>

In your Controller class:

...

import org.springframework.validation.Validator;

...

@Autowired
private Validator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
  binder.setValidator(validator);
}

See this section of the reference manual for details.

Upvotes: 5

Related Questions