Domanda

I have implemented a bean with hibernate and hibernate validation. This is the field I am testing on.

@NotBlank(message ="test.test" )
private String test;

I have a file

messages.properties

and

 messages_en.properties

that I use. Spring.message tags work so the files can be found and are used in the system elsewhere. I get "test.test" as my validation error when I try to store an object with that field empty and not error message in messages.properties. What am I missing?

È stato utile?

Soluzione 2

The problem was that i was missing this in my configuration. Also message="{test.test}" was necessary.

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

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="messageInterpolator">
        <bean class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator">
            <constructor-arg index="0">
                <bean
                    class="org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator">
                    <constructor-arg index="0" ref="messageSource" />
                </bean>
            </constructor-arg>
        </bean>
    </property>
</bean>

Altri suggerimenti

You should try like this by enclosing key name with curly braces. This syntax is different than Java from the localization files. It's followed with Spring/Hibernate Validation thru Validation API.

@NotBlank(message="{test.test}") private String test;

Only below worked for me:

  1. Create ValidationMessages.properties in "resources" directory of maven project with the below message property:

    app.validation.notempty.msg=must be populated
    
  2. Then, in dto class:

    @NotEmpty(message = "{app.validation.notempty.msg}")
    private String fieldName;
    
  3. Fially validate as shown below. Please note I found provider HibernateValidator.class is mandatory to take the values from .properties file.

    ValidatorFactory factory = Validation.byProvider( 
    HibernateValidator.class )
            .configure()
            .buildValidatorFactory();
    Validator validator = factory.getValidator();
    

Hope this helps someone.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top