thymeleaf - 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>
解决方案
您使用单选按钮的方式没有意义。选择的单选按钮是单个值,但您正试图将其绑定到数组:(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>
推荐阅读
- c++ - 使用指针数组上的重载运算符进行排序
- terraform - 在 Terraform 0.12 中迭代地图
- python - 将 Slugs 添加到 URL 模式
- android - 如何将 MediaQueryData 添加到空间填充?
- java - 在 Java 14 中定义 Records 类(JEP 359:Records(Preview))的括号内空格的 IntelliJ 编辑器代码样式设置?
- r - R Studio 版本 1.2.5033 - 安装包问题第 1 部分
- php - Laravel SweetAlert 在验证失败块中不起作用
- validation - 如何使用 Yup 验证电话号码但不是必需的?
- dynamics-crm - CRM 365 - 隐藏站点地图区域
- python - Python:“浮点”对象不能解释为整数?