简体   繁体   中英

Spring validation @AssertTrue custom error code/message

I'm using javax.validation.constraints.AssertTrue annotation in a form object of a Spring MVC project (Spring Boot 1.4.2).

My class is similar to this:

public class CommandForm {

    @NotEmpty
    @Email
    private String email;

    // ...

    @AssertTrue(message="{error.my.custom.message}")
    public boolean isValid(){
        // validate fields
    }
}

Method isValid is invoked correctly and validation process works fine, but my custom error code is not resolved correctly.

I have a error.my.custom.message field in my message.properties file, but when validation fails I get the "{error.my.custom.message}" string as error message instead of the resolved message.

What's wrong with my code? Is this the right syntax to set a custom error code?

I think the only issue that you might have is that Java Validation API (JSR-303) , by default, reads those messages from a file named: ValidationMessages.properties (under /resources ).

Create a file with that name and move your message(s) over there...then try again. It should work!

NOTE: You can change the filename though, but "by convention" is named like that.

Move your messages to the ValidationMessages.properties file Or override getValidator() method of your WebMvcConfigurerAdapter to make your custom message.properties get loaded by spring, as follows:

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebController extends WebMvcConfigurerAdapter {

    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("message");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

}

I found the solution after a bit of debugging.

The easiest way to set a custom message was to simply define an AssertTrue.commandForm.valid field in my message.properties .

No need to set the message argument in the @AssertTrue annotation.

Ooo, a golden oldie. But I think that every answer here actually missed the point. I figure you have moved past this, but I'm answering it anyways for future readers. I see two issues:

Most important: you are trying to test the validation for the class, not the messages in the properties file. So the string you get back is actually what you want to test for: "{error.my.custom.message}".

Now if you want to test to make sure that the properties file has the correct strings then simply use that identifier to go to the properties file and get the string to check. We usually don't check those kinds of things because that's the kind of thing that is subjective and messages could change frequently. And then are you going to do that for all the properties files for different locales?

Now the second point is that you really should be putting this into real unit and integration tests that will run in the DevOps pipeline (JUnit, TestNG?). I would avoid putting assertions (@Assert) in the class definition. Which is borne out by the documentation saying that @Assert is really for internal use by the framework, not you: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/Assert.html .

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