Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
davioooh Avatar asked Sep 18 '25 22:09

davioooh


2 Answers

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.

like image 200
davioooh Avatar answered Sep 21 '25 12:09

davioooh


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.

like image 28
Joel Mussman Avatar answered Sep 21 '25 10:09

Joel Mussman