I am using spring boot and thymeleaf for a web application.
I want to customize the validation error messages instead of using the default ones. I found the way to do it is creating a file called messages.properties with the constraints and the message. I also found I can create custom messages based on the class I am targeting and I can also use internationalization methods based on this.
In order to override the default messages I created my own messages.properties file:
Size.message=El tamño no es correcto
NotNull.message=No puede ser nulo
Min.message=No cumple con el minimo
I set the constraints in my class:
public class Person {
@Size(min=2, max=30)
private String name;
@NotNull
@Min(value = 18L)
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
This is my form:
<form action="#" th:action="@{/form}" th:object="${person}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}"/></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}"/></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name error</td>
</tr>
<tr>
<td>
<button type="submit">Enviar</button>
</td>
</tr>
</table>
</form>
And I placed the messages.properties in the resources folder:
According to these links I am doing correctly:
Thymeleaf : How to use Custom Message Key in JSR-303 Annotation
How to include message.properties with thymeleaf
But it still not display the custom error messages I wrote.
Any suggestion? Thanks in advance for your help.
GitHub with the sample code: https://[email protected]/MichaelKnight/ValidandoFormularios.git
Finally I got it!
Instead of the ClassName I had to use the object name and it works like a charm. NotNull.person.age=THE AGE CANNOT BE NULL!!!!
I uploaded the code to github for further references for any fellow member.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments