Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 Hibernate validator localized messages

I try to get working localization with custom hibernate messages but I can't make it work. My class that is validated looks like this:

@Entity
@Table(name = "USERS")
public class UserEntity extends AbstractBaseEntity implements UserDetails {

    @NotNull
    @Column(unique = true, nullable = false)
    @Size(min = 5, max = 30)
    private String username;

This is part of my spring configuration:

<!-- Localization of hibernate messages during validation!-->
<bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:validation" />
</bean>

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

In resources I have two validations files: validation_en.properties and validation_pl.properties Here is example entry:

NotNull.UserEntity.username=Username can't be empty!

And when I am displaying validation errors I see standard message "may not be null" instead of my custom and localised one. Wham I am doing wrong? Thanks in advance for help, Best Regards

like image 369
John Avatar asked Feb 14 '23 13:02

John


1 Answers

You need to do is @NotNull(message = "{error.username.required}")

@Entity
@Table(name = "USERS")
public class UserEntity extends AbstractBaseEntity implements UserDetails {

@NotNull(message = "{error.username.required}")
@Column(unique = true, nullable = false)
@Size(min = 5, max = 30)
private String username;

In validation_en.properties properties file in your resource folder

error.username.required=Username can't be empty!

In spring configuration:

<mvc:annotation-driven validator="validator">
</mvc:annotation-driven>

 <!-- Localization of hibernate messages during validation!-->
 <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:validation" />
 </bean>

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

Also leave a comment if this does not work for you. So I can help you further.

like image 176
prem30488 Avatar answered Feb 17 '23 20:02

prem30488