Thymeleaf: display global errors by error code

Viewed 1859

How can I display multiple global errors in my templates, by their respective error code?

When rejecting on the binding result, the first argument is the error code. How can I use this when displaying the errors in my template?

Use case: I use custom validation rules in my controller (such as duplication checks) and I want to show the global errors on different places in my form.

Ex:

public String myPage(..., BindingResult result) {
    result.reject("errorCode1", "Error 1 happened");
    result.reject("errorCode2", "Error 2 happened");
    return "my-view"
}

In my Thymeleaf template, I can display all errors at once:

<form th:object="${myForm}" method="post">
    <p th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}"></p>
</form>

But how can I print only the error with error code errorCode1?

2 Answers

I think there is no way to do that. I suggest you to create another field in your object (myForm) and assign the error in BindingResult with rejectValue. Then you can validate the error on template:

public String myPage(..., BindingResult result) {
    result.reject("errorCode1", "Global Error Happened");
    result.rejectValue("newField", "Error 2 happened");
    return "my-view"
}

<form th:object="${myForm}" method="post">
    <p th:if="${#fields.hasGlobalErrors()}" th:errors="*{global}"></p>
    <p th:if="${#fields.hasErrors('newField')}" th:errors="*{newField}"></p>
</form>

Hope this helps!

It took me a bit to figure out, but it works like this:

public String myPage(..., BindingResult result) {
    result.reject("errorCode1", "errorCode1");
    result.reject("errorCode2", "errorCode2");
    return "my-view"
}

Important: errorCode1 must not be a key of a message source!

<form th:object="${myForm}" method="post">
    <p th:if="${#lists.contains(#fields.globalErrors(), &quot;errorCode1d&quot;)}" th:text="Error 1 happened"></p>
</form>

Important: Use &quot; to indicate the string. th:text may contain a message key like th:text="#{error.code1}"

Related