Проверка Spring + Thymleaf для сгенерированных полей Dynami c - PullRequest
0 голосов
/ 09 января 2020

Я пытаюсь проверить поле ввода, сгенерированное динамически. код ниже даст нам больше входных данных:

код от HTML:

 <th:block th:each="word,itera : ${credentialsForm.credentialRequirements}">
          <div class="rtr_credential" style="display: inline-block;">
            <span th:text="${word.attribute}" ></span>
            <input type="hidden"  th:name="|credentialRequirements[${itera.index}].attribute|" th:value="${word.attribute}">
          </div>
          <div class="rtr_credential" style="display: inline-block;">
            <input type="text"  name="userValue" th:field="*{credentialRequirements[__${itera.index}__].userValue}" class="userValue" maxlength="30"
              th:classappend="${#fields.hasErrors('userValue')}? has-error : ''">  
          </div>
        </th:block>

Это выдает ошибку, поскольку userValue отсутствует в credentialsForm и если я включу th: classappend = " $ {# fields.hasErrors ('{credentialRequirements [__ $ {itera.index} __]. userValue}')}? has-error: '' "> это вызовет ошибку индексации. Java структура класса:

public class CredentialRequirementForm {


    private List<CredentialRequirements> credentialRequirements;

    public List<CredentialRequirements> getCredentialRequirements() {
        return credentialRequirements;
    }
    public void setCredentialRequirements(List<CredentialRequirements> credentialRequirements) {
        this.credentialRequirements = credentialRequirements;
    }

}

CredentialRequirements. java

public class CredentialRequirements {


    private String attribute;
    private String carrierDescription;
    @NotBlank
    @NotNull
    private String userValue;



    public CredentialRequirements() {
        super();
        // TODO Auto-generated constructor stub
    }

    public CredentialRequirements(String attribute, String carrierDescription, String userValue) {
        super();
        this.attribute = attribute;
        this.carrierDescription = carrierDescription;
        this.userValue = userValue;
    }

    public String getAttribute() {
        return attribute;
    }
    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
    public String getCarrierDescription() {
        return carrierDescription;
    }
    public void setCarrierDescription(String carrierDescription) {
        this.carrierDescription = carrierDescription;
    }


    public String getUserValue() {
        return userValue;
    }

    public void setUserValue(String userValue) {
        this.userValue = userValue;
    }

    @Override
    public String toString() {
        return "CredentialRequirements [attribute=" + attribute + ", carrierDescription=" + carrierDescription
                + "]";
    }

}

Как проверять userValues, он генерируется динамически, иногда только 1 атрибут, а иногда 5 атрибутов , Я также пытаюсь Jquery проверить, но путаю, как реализовать.

Ответы [ 2 ]

0 голосов
/ 13 января 2020

Спасибо всем за ваш ответ и комментарии. Мне нужно доставить код, поэтому для подтверждения используйте Jquery и Javascript: найдите код ниже:

submitHandler : function(form) {
            let invalid = 0
            $(  ".userValue" ).removeClass( "has-error" )
            $( ".userValue" ).each(function() {

              if($( this ).val() == "" ) {
                invalid++
                $( this ).addClass( "has-error" );
              }
            });
            if(invalid == 0){
                //some logic
                form.submit();
            } 
        }
0 голосов
/ 09 января 2020

Почему бы вам просто не использовать атрибут th:field для привязки полей HTML к полям вашей сущности? Затем вы можете добавить div с сообщением об ошибке (если будет ошибка проверки):

<th:block th:each="word,itera : ${credentialsForm.credentialRequirements}">
    <div class="rtr_credential" style="display: inline-block;">
        <span th:text="${word.attribute}" ></span>
        <input type="hidden" th:field="*{credentialRequirements[__${itera.index}__].attribute}">
    </div>
    <div th:if="${#fields.hasErrors('credentialRequirements[__${itera.index}__].userValue')}"  th:errors="*{credentialRequirements[__${itera.index}__].userValue}">
        Error message
    </div>
    <div class="rtr_credential" style="display: inline-block;">
        <input type="text"  name="userValue" th:field="*{credentialRequirements[__${itera.index}__].userValue}" class="userValue">  
    </div>
</th:block>
...