简体   繁体   中英

spring mvc validation messages

I have a problem figuring out how to pass validation properties from spring to the externalized messages. I am using spring 4, and already included "validation-api-1.1.0.Final" and "hibernate-validator-5.2.1.Final".

my Model:

@Size(min=20, max=64)
private String email;

I am still getting the message of " email shouldn't be empty TCH {2} {1} {0} " when I return to the form.

My validationMessages.properties has the following line in it:

  • Size.virement.email=email shouldn't be empty TCH {2} {1} {0}

I also tried using {min} and {max} , as well as %1 and %0 . None of these work.

My xml config for spring has the following configuration:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>classpath:content/ValidationMessages</value>
                <value>classpath:content/Language</value>
                ...
            </list>
        </property>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

I also did include the spring-context-4.1.5.RELEASE library.

Any idea ??
Note that I am using thymeleaf to render the view.

Thx in advance.

You basically have an error message template, which you would like to populate with the values of the given constraint.

I think you can achieve this with an custom ConstraintValidor.

See the Hibernate reference here, especially the section 3.1.2.1: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html

I hope it gives some idea!

Try to add:

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

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

Example:

Size.user.name=Invalid username

And please note that user in is value of ModelAttribute in your Controller ( @ModelAttribute("user") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM