首页 > 解决方案 > Thymeleaf 单选按钮 th:field 检查验证

问题描述

我正在尝试验证使用 th:each 创建的单选按钮的输入。在 html 中的输入输出中使用 th:field checked="checked" 这使得一个单选按钮被选中,这是我不想要的。如果我输入 name="field" 则不会发生这种情况,但是不会发生对字段的验证,因为我不会使用 th:field。

<form th:action="@{/dosomething}" th:object="${Object}" method="post">                                  
<div th:each="op : *{options}"> 
<input type="radio" th:field="*{options}" th:value="${op.id}"     th:id="${opStat.index}"/>                         
<label th:for="${opStat.index}" th:text="${op.optiontext}">Option   Text</label>
<button type="submit">Next</button>                 
</form>

<form action="/dosomething" method="post">                                  
<div>   
<input type="radio" value="1" id="0" name="options" checked="checked"/>                         
<label for="0">A</label>
</div>                                  
<div>   
<input type="radio" value="3" id="1" name="options" checked="checked"/>                         
<label for="1">B</label>
</div>                                  
<div>   
<input type="radio" value="4" id="2" name="options" checked="checked"/>                         
<label for="2">C</label>
</div>                                  
<div>   
<input type="radio" value="2" id="3" name="options" checked="checked"/>                         
<label for="3">D</label>
</div>              
<button type="submit">Next</button>             
</form>

标签: thymeleaf

解决方案


您使用单选按钮的方式没有意义。选择的单选按钮是单个值,但您正试图将其绑定到数组:(th:field="*{options}"而不是单个字段,th:field="*{selectedOpId}"例如)。

th:object应该有一个字段来存储单选按钮选择的结果,并且您th:each应该迭代常规模型属性。像这样的东西:

<form th:action="@{/dosomething}" th:object="${Object}" method="post">
    <th:block th:each="op : ${options}">
        <input type="radio" th:field="*{chosenOptionId}" th:value="${op.id}" th:id="${opStat.index}"/>                         
        <label th:for="${opStat.index}" th:text="${op.optiontext}">Option Text</label>
    <th:block>

    <button type="submit">Next</button>                 
</form>

推荐阅读