Skip to content

How to control fields.hasErrors() and bindingResult manually

I’m trying to check if I have a List with items. So I use this code in my HTML

<div class="form-group-petit row">
                <div class="col-sm-12">
                    <table class="table center" id="tableSelectedEstudis">
                        <col style="width:80%">
                        <col style="width:20%">
                        <!--<col style="width:10%">-->
                            <th scope="col" data-th-text="#{edicio.estudis}"></th>
                            <th scope="col" data-th-text="#{edicio.estudis.vigent}">Vigent</th>
                           <!--  <th scope="col" data-th-text="#{label.accions}">Accions</th> -->
                            <tr th:each="estudi : *{listEstudis}" >
                                <td scope="row" th:text="${estudi.codiEstudi +' - '+ estudi.memo}"/>
                                <td scope="row" th:text="${estudi.vigentSN}"/>
                               <!--  <td>
                                    <span class="link" th:attr="data-codiestudi =${estudi.codiEstudi}" id="eliminarEstudi" title="Elimina estudi" th:unless="*{altaOk} OR *{altaKo}"><i class="oi oi-delete"></i></span>
                                </td> -->
            <label class="error col-sm-10" th:if="${#fields.hasErrors('listEstudis')}" th:errors="*{listEstudis}"></label>

Normally I should add @NonEmpty label in the form and let Spring work automatically. In my case, I can’t do it this way and I need to add the error manually. So I do this in my controller:

    String[] codes = { "NotEmpty.admEdicionsDetallForm.listEstudis", "NotEmpty.listEstudis",
            "", "NotEmpty" };
    String objectName = "admEdicionsDetallForm";
    Object[] objects = { new DefaultMessageSourceResolvable(
            new String[] { "admEdicionsDetallForm.listEstudis", "listEstudis" }, null, "listEstudis") };
    if (llistatEstudis.isEmpty()) {
                new ObjectError(objectName, codes, objects, "És obligatori seleccionar almenys un estudi"));

But the message is not showing when I try to do it manually, howerver if I do it with the @NonEmpty lable it works.


The rejectValue() method is used to add a validation error to the BindingResult object.

So, in your code, instead of:

    .addError(new ObjectError(objectName, codes, 
        objects, "És obligatori seleccionar almenys un estudi"));

Try with:

bindingResult.rejectValue("listEstudis", "error. listEstudis", 
    "És obligatori seleccionar almenys un estudi!");