'Spring MVC and Thymeleaf custom error message type conversion

I have an entity as follow :

@Entity
public class MyEntity {

    @Column(name = "id")
    @Id @GeneratedValue
    private Long id;
    private int SiteId;
   //...getters & setters etc..
}

A method in my @Controller :

@RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(@Valid @ModelAttribute("myEntity") MyEntity myEntity, BindingResult result) {

        if (result.hasErrors()) { 
            return "edit"; 
        } 
        myEntityRepository.save(myEntity);
        return "redirect:/home"; 
    }

and in my edit.html file :

<form name="form"  th:action="@{/edit}" th:object="${myEntity}" method="post">
    <div class="form-group col-sm-3">
        <label class="control-label" for="siteId">Site ID</label>
        <input class="form-control" type="text" th:field="*{siteId}"/>
        <p th:if="${#fields.hasErrors('siteId')}" 
        class="label label-danger" th:errors="*{siteId}">My custom error message</p>
    </div>
    <div class="form-group">
        <input type="submit" value="Confirme" class="btn btn-primary" />
    </div>
</form>

I get this message showing under my siteId field : Failed to convert property value of type [java.lang.String] to required type [int] for property sectorId; nested exception is java.lang.NumberFormatException: For input string: "random string" instead of the message I want to show, which is My custom error message



Solution 1:[1]

If you look into your BindingResult result in case of the conversion failure, you would see:

BindingResult.errors[0].codes = [
    0 = "typeMismatch.myEntity.sectorId"
    1 = "typeMismatch.sectorId"
    2 = "typeMismatch.int"
    3 = "typeMismatch"
]

That means, that if you want to change the error message, you need to go to your localization file with messages (such as messages.properties) and set the error message there:

typeMismatch.myEntity.sectorId = Sector must be a number

or generically for any int:

typeMismatch.int = Must be a number

For more about localization of messages in Spring MVC, see https://www.baeldung.com/spring-custom-validation-message-source.

Solution 2:[2]

Try ading this:

typeMismatch.classNameWrittenLikeThat.fieldName = custom text to show as error

to your messages.properties

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shine Developer
Solution 2